Skip to content

Instantly share code, notes, and snippets.

@benfb
Created November 4, 2012 23:57
Show Gist options
  • Save benfb/4014439 to your computer and use it in GitHub Desktop.
Save benfb/4014439 to your computer and use it in GitHub Desktop.
AliceCount
// add import statements
import java.util.*;
import java.io.*; //imports the io library. Note: Importing java.* does NOT work
// create class AliceCount
public class AliceCount
{
// create main method - remember to catch the exception
public static void main(String[] args)
throws FileNotFoundException //keeps the code compiling even if a FileNotFound exception appears
{
// instantiate Scanner object using text file
Scanner in = new Scanner(new File("alice.txt")); //creates a scanner that scans the file alice.txt
// instatiate PrintWriter with output file name
PrintWriter output = new PrintWriter(new FileOutputStream("output.txt")); //creates printwriter objects to write to the files in parentheses
PrintWriter ew = new PrintWriter(new FileOutputStream("e.txt"));
PrintWriter aw = new PrintWriter(new FileOutputStream("a.txt"));
PrintWriter tw = new PrintWriter(new FileOutputStream("t.txt"));
PrintWriter ow = new PrintWriter(new FileOutputStream("o.txt"));
PrintWriter iw = new PrintWriter(new FileOutputStream("i.txt"));
// create variable to track the number of words in the text
int wc = 0; //creates wc variable
// create variable to track each of the letters
int lc = 0; //initializes lc (total letter count), a, e, t, o, and i letter counters
int a = 0;
int e = 0;
int t = 0;
int o = 0;
int i = 0;
// loop through the file
while(in.hasNext()) //while there is a next line in the file called by the "in" object
{
String ln = in.next();
wc++; //increment word count every time the loop is run
if(ln.indexOf('a') > -1){ //if an a is present in the string ln
a++; //increment the a counter
aw.println(ln);} //and print the word ln to the file that aw can print to
if(ln.indexOf('e') > -1){
e++;
ew.println(ln);}
if(ln.indexOf('t') > -1){
t++;
tw.println(ln);}
if(ln.indexOf('o') > -1){
o++;
ow.println(ln);}
if(ln.indexOf('i') > -1){
i++;
iw.println(ln);}
}
// calculate the percentage of words containing the character
double aav = ((double)a / (double)wc) * 100; //simple division (typecasts as double to make devision precise)
aw.println(aav); //prints the percentage of 'a's compared to other letters
aw.println(a); //prints the amount of 'a's in alice.txt to a.txt
double eav = ((double)e / (double)wc) * 100;
ew.println(eav + "%");
ew.println(e);
double tav = ((double)t / (double)wc) * 100;
tw.println(tav + "%");
tw.println(t);
double oav = ((double)o / (double)wc) * 100;
ow.println(oav + "%");
ow.println(o);
double iav = ((double)i / (double)wc) * 100;
iw.println(iav + "%");
iw.println(i);
// close the files
aw.close();
ew.close();
tw.close();
ow.close();
iw.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment