Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 我的项目赢了';不要要求用户输入文件中的某个事件_Java_String_Java.util.scanner_Find Occurrences - Fatal编程技术网

Java 我的项目赢了';不要要求用户输入文件中的某个事件

Java 我的项目赢了';不要要求用户输入文件中的某个事件,java,string,java.util.scanner,find-occurrences,Java,String,Java.util.scanner,Find Occurrences,因此,我正在制作一个程序,从我的文件中读取内容,并允许用户输入一个单词来查看单词的出现。 它运行正常,但不要求用户输入单词,我无法解释原因,代码如下: import java.util.*; import java.io.*; public class WordOccurence { public static void main(String[] args) throws IOException { int wordCount=0; int word =

因此,我正在制作一个程序,从我的文件中读取内容,并允许用户输入一个单词来查看单词的出现。 它运行正常,但不要求用户输入单词,我无法解释原因,代码如下:

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);
    }
}

您的代码中几乎没有错误,这个版本应该可以像您预期的那样工作(我插入了一些注释,试图解释如何修复)

不要忘记关闭扫描仪:

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

如果您希望它询问用户,如在弹出框中,您可以执行以下操作:

String input = JOptionPane.showInputDialog("Your message");

编辑:您不需要扫描仪,除非您正在对输入进行迭代。

您能指出您认为哪行代码正在从用户处获取关于扫描哪个单词的输入吗?那么,下一个要读取的标记是整数吗?当循环条件为真时,您是否检查了
?另外,对于
系统,您只需要一个
扫描仪
。在
中,只需使用
扫描
。除非您想以某种方式对其进行迭代,否则为什么要“扫描”由
showInputDialog()返回的
字符串
?我通常会选择不关闭标准输入流
系统。
,因为它无法重新打开。如果你不打算再次使用它,那也没关系!是的,很抱歉,它是从我以前的项目更新的,该项目是打印文件的数量。但是谢谢你把它弄清楚。我能清楚地看到这个问题。多谢各位sir@d.j.brown你是对的,但在这个简单的“主要”中,我总是在最后关闭扫描仪,只是因为看不到警告“扫描仪永远不会关闭”;)@我很高兴在某种程度上帮助了你。
String input = JOptionPane.showInputDialog("Your message");