Reputation: 51
I'm writing a program that reads sports data from a text file. Each line has strings and ints mixed together, and I'm trying to read just the scores of the teams. However, even though the lines have ints, the program immediately goes to the else statement without printing out the scores. I have the two input2.nextLine()
statements so that it skips two header lines that have no scores. How can I fix this?
Here's the code:
public static void numGamesHTWon(String fileName)throws FileNotFoundException{
System.out.print("Number of games the home team won: ");
File statsFile = new File(fileName);
Scanner input2 = new Scanner(statsFile);
input2.nextLine();
input2.nextLine();
while (input2.hasNextLine()) {
String line = input2.nextLine();
Scanner lineScan = new Scanner(line);
if(lineScan.hasNextInt()){
System.out.println(lineScan.nextInt());
line = input2.nextLine();
}else{
line = input2.nextLine();
}
}
}
Here is the top of the text file:
NCAA Women's Basketball
2011 - 2012
2007-11-11 Rice 63 @Winthrop 54 O1
2007-11-11 @S Dakota St 93 UC Riverside 90 O2
2007-11-11 @Texas 92 Missouri St 55
2007-11-11 Tennessee 76 Chattanooga 56
2007-11-11 Mississippi St 76 Centenary 57
2007-11-11 ETSU 75 Delaware St 72 O1 Preseason NIT
Upvotes: 0
Views: 94
Reputation: 2006
Method hasNextInt()
try to check immediate string is int ? . So that condition is not working.
public static void numGamesHTWon(String fileName) throws FileNotFoundException {
System.out.print("Number of games the home team won: ");
File statsFile = new File(fileName);
Scanner input2 = new Scanner(statsFile);
input2.nextLine();
input2.nextLine();
while (input2.hasNextLine()) {
String line = input2.nextLine();
Scanner lineScan = new Scanner(line);
while (lineScan.hasNext()) {
if(lineScan.hasNextInt()) {
System.out.println(lineScan.nextInt());
break;
}
lineScan.next();
}
line = input2.nextLine();
}
}
Please try this code.
Upvotes: 0