提问人:Mahesh Divate 提问时间:11/24/2021 最后编辑:gkhaosMahesh Divate 更新时间:11/24/2021 访问量:66
打印段落中的字数
Printing number of words in paragraph
问:
我以段落的形式接受用户输入,我必须计算段落中的单词,直到段落。用户不会从控制台输入“退出/停止”关键字,而只会输入段落。我没有得到所需的输出。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
答:
0赞
Devck - DC
11/24/2021
#1
我已经尝试使用您的代码,删除这一行很好:
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);
}
}
你已经在读 while 句子中的那一行了,所以它读了两遍
评论
0赞
Mahesh Divate
11/24/2021
但这只会读取一行。我想读这一段..
1赞
Krystian Kulik
11/24/2021
#2
首先,关于删除重复的 str = br.readLine() 的注释是完全有效的,但程序仍然无法正常工作。因为 bellow 语句,行中的第一个单词将被忽略且不计算在内(行不一定以空格开头):
if (str.charAt(i) == ' ' && str.charAt(i+1)!=' ')
您的程序也不可能只读取一个段落并停止,因为它被设计为始终等待下一行。在粘贴输入后按其他回车键时停止怎么样?
无论如何,这个版本应该效果更好:
public static void main(String[] args) throws IOException {
InputStreamReader r = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(r);
int wordCount = 0;
String str;
while (!(str = br.readLine()).isEmpty()) {
wordCount += Arrays.stream(str.split("\\s+")).filter(word -> !word.isEmpty()).count();
}
System.out.println(wordCount);
}
上一个:尝试压缩文件时出现随机“Zlib 输入流意外结束”异常
下一个:如何到达文件结束?
评论
str = br.readLine()
str = br.readLine()