gpt4 book ai didi

Java简单统计文件中的单词数

转载 作者:行者123 更新时间:2023-12-01 04:57:36 24 4
gpt4 key购买 nike

我正在创建一个简单的程序,用于计算论文中的字数、行数和总字符数(不包括空格)。这是一个非常简单的程序。我的文件可以编译,但是当我运行它时,我收到此错误:

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1347)
at WordCount.wordCounter(WordCount.java:30)
at WordCount.main(WordCount.java:16)

有谁知道为什么会这样吗?

 import java.util.*;
import java.io.*;
public class WordCount {
//throws the exception
public static void main(String[] args) throws FileNotFoundException {
//calls on each counter method and prints each one
System.out.println("Number of Words: " + wordCounter());
System.out.println("Number of Lines: " + lineCounter());
System.out.println("Number of Characters: " + charCounter());

}

//static method that counts words in the text file
public static int wordCounter() throws FileNotFoundException {
//inputs the text file
Scanner input = new Scanner(new File("words.txt"));
int countWords = 0;
//while there are more lines
while (input.hasNextLine()) {
//goes to each next word
String word = input.next();
//counts each word
countWords++;
}
return countWords;
}

//static method that counts lines in the text file
public static int lineCounter() throws FileNotFoundException {
//inputs the text file
Scanner input2 = new Scanner(new File("words.txt"));
int countLines = 0;
//while there are more lines
while (input2.hasNextLine()) {
//casts each line as a string
String line = input2.nextLine();
//counts each line
countLines++;
}
return countLines;
}

//static method that counts characters in the text file
public static int charCounter() throws FileNotFoundException {
//inputs the text file
Scanner input3 = new Scanner(new File("words.txt"));
int countChar = 0;
int character = 0;
//while there are more lines
while(input3.hasNextLine()) {
//casts each line as a string
String line = input3.nextLine();
//goes through each character of the line
for(int i=0; i < line.length(); i++){
character = line.charAt(i);
//if character is not a space (gets rid of whitespace)
if (character != 32){
//counts each character
countChar++;
}
}
}
return countChar;
}
}

最佳答案

如果不查看文件,我无法真正说出问题的确切原因(甚至可能当时也没有)。

   while (input.hasNextLine()) {
//goes to each next word
String word = input.next();
//counts each word
countWords++;
}

是你的问题吗?如果您在 while 条件语句中使用 input.hasNextLine(),请使用 input.nextLine()。由于您使用的是 input.next(),因此您应该在 while 循环条件语句中使用 input.hasNext()

关于Java简单统计文件中的单词数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13854073/

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