所以我正在制作一个程序,它从我的文件中读取并允许用户输入一个单词以查看该单词的出现情况。 它运行正常,但不要求用户输入单词,我不明白为什么,这是代码:
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);
}
}
最佳答案
您的代码中几乎没有错误,此版本应该可以按您的预期工作(我插入了注释试图解释如何修复)
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);
}
}
不要忘记关闭扫描仪:
scan.close();
scr.close();
关于java - 我的程序不会要求用户输入文件中出现的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40643545/