【问题标题】:Printing number of words in paragraph打印段落中的字数
【发布时间】: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


【解决方案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语句中的那一行,所以它读了两次

【讨论】:

  • 但这只会读一行。我想读一段..
【解决方案2】:

首先,关于删除重复的 str = br.readLine() 的注释是完全有效的,但程序仍然无法正常运行。由于下面的语句,行中的第一个单词将被忽略且不计算在内(行不必以空格开头):

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

}

【讨论】:

    猜你喜欢
    • 2019-08-27
    • 2015-08-14
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    • 2022-10-05
    • 2023-01-02
    相关资源
    最近更新 更多