我试图阅读创建一个读取我制作的文本文件的基本类,并打印出每个特定行上的单词数。
我想要的输出是要在新行上打印的每个整数。例如,如果第一行有10个单词,第二行有23个,第三个有24个,我想:
10
23
24
但由于某些原因,我的代码正在给我
190
0
这是文件中的单词总数以及重置为0的时间。我做错了什么?
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class numWords {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("words.txt");
Scanner scanner = new Scanner(file);
int numWords = 0;
while (scanner.hasNextLine()) {
while (scanner.hasNext()) {
numWords++; //counts number of words
scanner.next(); //goes to the next word if available
}
System.out.println(numWords); //prints the number of words
numWords = 0; //resets it to 0
scanner.nextLine(); //goes to the next line
}
scanner.close();
}
}
我尝试过if语句说如果还没有行,那么我会使用scanner.close();.
答案 0 :(得分:2)
您的问题是scanner.next()将继续通过换行符。您希望单独获取每一行,然后执行单词计数并输出它。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class numWords {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("words.txt");
Scanner filescanner = new Scanner(file);
int numWords = 0;
while (filescanner.hasNextLine()) {
String line = filescanner.nextLine(); //pulls in next line
Scanner linescanner = new Scanner(line); //create new scanner for just this line
while (linescanner.hasNext()) {
numWords++; //counts number of words
linescanner.next(); //goes to the next word if available
}
System.out.println(numWords); //prints the number of words
numWords = 0; //resets it to 0
linescanner.close();
}
filescanner.close();
}
答案 1 :(得分:0)
这是另一种解决方案,在main
正文中仅使用三行代码:
public static void main(String[] args) throws IOException {
Files.lines(Paths.get("words.txt"))
.map(String::trim)
.forEach(line -> System.out.println(line.isEmpty()? 0 : line.split("\\s+").length));
}
或者,在Java 9中:
private final Pattern NON_WHITESPACE = Pattern.compile("\\S+");
public static void main(String[] args) throws IOException {
Files.lines(Paths.get("words.txt"))
.forEach(line -> System.out.println(NON_WHITESPACE.matcher(line).results().count()));
}
(理想情况下,Files.lines()
应该在资源中试用,但为了简洁起见我将其遗漏了,因为这是main()
方法中唯一的语句,因此文件将在关闭时关闭main()
返回。)
答案 2 :(得分:-1)
在while
循环中,您可以将整行(按空格)拆分为String array
,然后只计算条目数。
String[] words;
while ((line = br.readLine()) != null) {
words = Pattern.compile("\\s+").split(line);
System.out.println(words.length);
}
注意:我使用了BufferedReader