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
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
I think it's easier to analyze lines by making a String variable and setting it equal to the next line. It's easier to parse a string. Also why ru doing inFile.equals() in file your Scanner so that would equal a Scanner object not a string.
Iterate through the file like this:
While(inFile.hadNextLine()) {
String nxtline = scan.nextLine():
If(nxtLine.equals("BB")
Your code here repeat this for your other if statements.
I hope this helped if it did let me know in a comment.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.