gpt4 book ai didi

java - 尝试从txt文件中逐行获取字数

转载 作者:行者123 更新时间:2023-12-02 12:05:48 26 4
gpt4 key购买 nike

我正在尝试创建一个基本类,该类读取我制作的文本文件,并打印出每个特定行上的字数。

我想要的输出是将每个整数打印在新行上。例如,如果第一行有 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();。

最佳答案

您的问题是 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();
}

关于java - 尝试从txt文件中逐行获取字数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46915166/

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