I’m creating a code that counts how many of each word is in a file, then adds to a variable. At the end, it prints out the variables. However, the outputs are always 0.
I originally had the while loop as a for loop, and I changed that to avoid another error, and I made sure that it’s scanning the correct file. The variables are correctly connected as well. However, no matter what’s in the file, the code always outputs 0 for every variable.
Example Code
public class Example{
public static void main(String [] args) {
//Setting the variables
int var1 = 0;
int var2 = 0;
int var3 = 0;
//Establishing the file and scanner
String searchRes;
File file = new File("Example.txt");
Scanner scan= new Scanner("Example.txt");
//The while loop
while(scan.hasNextLine()) {
searchRes = scan.nextLine();
if (searchRes.equals("FirstWord")) {
var1++;
}
if (searchRes.equals("SecondWord")) {
var2++;
}
if(searchRes.equals("ThirdWord")) {
var3++;
}
}
//Printing results
System.out.println("First: " + var1);
System.out.println("Second: " + var2);
System.out.println("Third: " + var3);
}
}
Sample File
FirstWord
ThirdWord
FirstWord
FirstWord
SecondWord
Expected Output
First: 3
Second: 1
Third: 1
Actual Output
First: 0
Second: 0
Third: 0
Why does it always output 0? How can I fix this bug?
>Solution :
The issue in your code is with the way you’re creating the Scanner object. You’re currently passing the file name as a string to the Scanner constructor, which is not correct.
Instead, you need to pass the File object itself to the Scanner constructor.
You just need to update the Scanner creation line to use the File object like this:
Scanner scan = new Scanner(file);