打印段落中的字数

Printing number of words in paragraph

提问人:Mahesh Divate 提问时间:11/24/2021 最后编辑:gkhaosMahesh Divate 更新时间:11/24/2021 访问量:66

问:

我以段落的形式接受用户输入,我必须计算段落中的单词,直到段落。用户不会从控制台输入“退出/停止”关键字,而只会输入段落。我没有得到所需的输出。EOFEOF

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
Java 数据结构 读取器 EOF

评论

0赞 gkhaos 11/24/2021
你跳过了一半的行。while 循环将首先计算条件,该条件将执行,如果 str 不为 null,它将执行并因此忽略第一行,以及之后的每第二行str = br.readLine()str = br.readLine()
0赞 9ilsdx 9rvj 0lo 11/24/2021
如果不定义什么是“单词”或“段落”,这个问题是不可能回答的。
0赞 Mahesh Divate 11/24/2021
@9ilsdx9rvj0lo段落将作为用户输入给出,我想计算该段落中的字数。我已经给出了示例 I/O

答:

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);

}