gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:02:35 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com