【发布时间】:2022-01-02 23:07:25
【问题描述】:
我以段落的形式接受用户输入,我必须计算段落中的单词直到EOF 段落。用户不会从控制台输入“退出/停止”关键字,而只会输入EOF 段落。我没有得到想要的输出。
import java.io.*;
public class CountWords
{
public static void main (String[] args) throws IOException
{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
int wordCount = 1;
String str;
while ((str=br.readLine())!=null)
{
str = br.readLine();
for (int i = 0; i < str.length(); i++)
{
if (str.charAt(i) == ' ' && str.charAt(i+1)!=' ')
{
wordCount++;
}
}
System.out.println(wordCount);
}
}
}
示例输入:-
This is a sample line of text
This is another line of text
This line is the 3rd line
This junk line contains 989902 99dsaWjJ8 015
This is the fifth and the last line of input
Output: 36
【问题讨论】:
-
你跳过了一半的行。 while 循环将从评估条件开始,该条件将执行
str = br.readLine(),如果 str 不为 null,它将执行str = br.readLine(),因此忽略第一行,以及之后的每第二行 -
如果不定义什么是“单词”或“段落”,就无法回答这个问题。
-
@9ilsdx9rvj0lo 段落将作为用户输入提供,我想计算该段落中的单词数。我已经给出了示例 i/o
标签: java data-structures bufferedreader eof