java - 我的程序不会要求用户输入文件中出现的事件

标签 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 =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/

相关文章:

java - Ruby 的比较器 <=> Vs. Java 的 .equals;比较字符串

java - 读取 CSV 文件时出现的问题让我困惑不已

java - 需要将数组传递给另一个类

java - Ubuntu 接管 Android。我们现在要用 GCC 还是 Android 的 Java NDK/SDK?

java - 正则表达式:删除 Java 中的第二对括号

php - 来自具有最常见单词的多个字符串的新字符串

java - 尝试在jpa中删除时的并发问题

Java扫描器对象跳行?

java - 使用扫描仪类输入时不打印字符串

java - rroReturn 类型方法缺失,YES_NO_OPTION 无法解决某些错误