The question is published on by Tutorial Guruji team.
I’m writing a program to read data from files with various sports statistics. Each line has information about a particular game, in say, basketball. If a particular line contains an “@” symbol, it means that one of the teams is playing at home. I’m trying to count the lines that contain an “@” and output that to the user as the Number of Games in which either team played at home. The first file has that 9 games were played at home for some team, but my output keeps printing out 0 rather than 9. How can I fix this?
Here’s the relevant code:
public static void numGamesWithHomeTeam(String fileName) throws IOException{ File statsFile = new File(fileName); Scanner input1 = new Scanner(statsFile); String line = input1.nextLine(); Scanner lineScan = new Scanner(line); int count = 0; while(input1.hasNextLine()){ if(line.contains("@")){ count++; input1.nextLine(); } else{ input1.nextLine(); } } System.out.println("Number of games with a home team: " + count); }
Answer
Your line variable always has the first line’s value. You should set line in the loop, something like that.
while(input1.hasNextLine()){ if(line.contains("@")){ count++; line = input1.nextLine(); } else{ line = input1.nextLine(); }
Edit: On the second look your code has other problem: the last line is never checked. You should not initialize line (set to null) and do the check after nextLine():
public static void numGamesWithHomeTeam(String fileName) throws IOException{ File statsFile = new File(fileName); Scanner input1 = new Scanner(statsFile); String line = null; Scanner lineScan = new Scanner(line); int count = 0; while(input1.hasNextLine()){ line = input1.nextLine(); if(line.contains("@")){ count++; } } System.out.println("Number of games with a home team: " + count);}