ant c ant c - 21 days ago 8
Java Question

My program won't ask the user for an input for an occurrence in a file

So i am making a program that reads from my file and allows the user to enter a word to see the occurrence of the word.
it runs properly but doesn't ask the user to enter a word and I'm stuck on why, here's the code:

import java.util.*;
import java.io.*;
public class wordOccurence {
public static void main(String[] args) throws IOException {
{
int wordCount=0;
int word =0;
Scanner scan=new Scanner(System.in);
System.out.println("Enter file name");
String fileName=scan.next().trim();
System.out.println("Enter the word you want to scan: ");
Scanner scr = new Scanner(new File(fileName));
// your code goes here ...
while(scr.hasNextInt()){
Scanner word2 = new Scanner(System.in);
String word1 = word2.next();

if (word1.equals(word2)){

word++;
}

}
System.out.println("Total words = " + word);

}
}
}

Answer

There are few errors in your code, this version should be work as you expected (I inserted comments trying to explain how to fix)

public static void main(String[] args) throws IOException {
{
    int word =0;
    Scanner scan=new Scanner(System.in);
    System.out.println("Enter file name");
    String fileName=scan.next().trim();
    System.out.println("Enter the word you want to scan: ");
    //You have to insert this line in order to ask the user to input the word to find
    String wordTofind=scan.next().trim();
    Scanner scr = new Scanner(new File(fileName));
    // You should fix also here: scan the file and look if the word is present
    while(scr.hasNext()){
        String word1 = scr.next();
        if (word1.equals(wordTofind)){
            word++;
        }
    }
    System.out.println("Total words = " + word);
    }
}

Don't forget to close the scanners:

scan.close();
scr.close();