【问题标题】:My program won't ask the user for an input for an occurrence in a file我的程序不会要求用户输入文件中出现的内容
【发布时间】:2016-11-16 22:31:14
【问题描述】:

所以我正在制作一个从我的文件中读取并允许用户输入一个单词以查看该单词出现的程序。 它运行正常,但不要求用户输入单词,我不知道为什么,这里是代码:

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

【问题讨论】:

  • 您能否指出您认为哪一行代码正在从用户那里获取有关要扫描的单词的输入?
  • 嗯,下一个要读取的标记是整数吗?您是否检查过while 循环条件是否为真?此外,System.in 只需要一个Scanner,只需使用scan

标签: java string java.util.scanner find-occurrences


【解决方案1】:

您的代码中几乎没有错误,这个版本应该可以正常工作(我插入了 cmets 试图解释如何修复)

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

【讨论】:

  • 我通常会选择不关闭标准输入流System.in,因为它无法重新打开。不打算再用也没关系!
  • 是的,很抱歉,它是从我之前的项目中更新的,该项目是打印文件的数量。但谢谢你清理它。
  • 我可以清楚地看到问题。非常感谢先生
  • @d.j.brown 你是对的,但在这个简单的“主要”中,我总是在最后关闭扫描仪,只是为了看不到“扫描仪永远不会关闭”的警告;)
  • @antc 很高兴在某种程度上帮助了你。
【解决方案2】:

如果你想让它询问用户,比如在弹出框中,你可以这样做:

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

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

【讨论】:

  • 除非您想以某种方式对其进行迭代,否则您为什么要“扫描”showInputDialog() 返回的 String
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-17
  • 1970-01-01
  • 2016-07-25
  • 2022-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多