Riley Denning Riley Denning - 2 months ago 6
Java Question

How can I use the scanner class to scan a text file, pick out certain phrases, and count them?

I'm new to learning java, and am having a lot of trouble on this particular assignment. Normally I can figure out a solution after a bit of research, but this has me stumped.
It's a program to read through a file with different combinations of the letters "G" and "B" (ex. GG, GB, BB, BG) and I have to count how many lines the file is as well as how many instances each of those combinations pop up. Any help would be very appreciated!
I tried searching through all posts and tried something, but now it seems that my program won't run (not giving me any error messages though).

Source Code:

import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class Family
{
public static void main(String[] args) throws IOException
{
//define variables
String lineRead = "";
int numberLines = 0; //# of lines
int bothMales = 0; //# of houses with both males
int bothFemales = 0; //# of houses with both females
int oneEach = 0; //#of houses with one male and one female
File fileName = new File("test1.txt");
Scanner inFile = new Scanner(new File("test1.txt"));

while (inFile.hasNextLine())
{
numberLines++;
inFile.nextLine();
Scanner check = new Scanner(inFile.nextLine());
while(check.hasNext())
{
if (inFile.equals("BB"))
{
bothMales++;
}
else if (inFile.equals("GG"))
{
bothFemales++;
}
else if ((inFile.equals("GB")) || (inFile.equals("BG")))
{
oneEach++;
}
}
}


System.out.println("Sample Size: " + numberLines);
System.out.println("Two Boys: " + bothMales );
System.out.println("Two Girls: " + bothFemales);
System.out.println("One Girl and One Boy: " + oneEach);


}//end main method
}//end class

Answer

You have to use the nextLine method of the Scanner

        while(check.hasNext())
        {
            String line = check.nextLine ();
            if (line.equals("BB"))
            {
                bothMales++;
            } 
            // etc
        }

Depending on your line, you maybe want to use the trim method on the String or use contains, rather than equals

Comments