【问题标题】:How to count words (including spaces)?如何计算单词(包括空格)?
【发布时间】:2018-03-04 05:25:26
【问题描述】:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class MyFirstProject {

  public static void main(String argv[]) throws IOException {

    //This line will create a buffered reader that reads from the system input using an input stream reader
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
    //input will contain the first line of input from the user   
    /**
     * This asks a question.
     */
    System.out.println("What is your input?");
    String input = bufferedReader.readLine();
    /**
     * This returns a valediction or the input.
     */
    if (input.equals("exit")) {
        System.out.println("GOODBYE!");
    }
    else {
        System.out.println(input);
    }


    }


/**
 * This counts the number of words (including spaces) in a string.
 * @param words The user input.
 * @return The number of words in a string.
 */
public static String numberOfWords(String words) {
  int count = 0;
  if (words.length() == 1) {
      count++;
      return (String.valueOf(count) + "word");
  }
  if (words.length() > 1) {
      for (int i = 0; i <= words.length(); i++) {
          if (words.charAt(i) == ' ') {
              count++;
          }
      }
      return (String.valueOf(count) + "words");
  }
  else {
      return (String.valueOf(count) + "words");
  }
}
}

我的问题很简单。我很难理解为什么我的代码不会返回输入中的单词数。输出应该是这样的,例如,如果用户在控制台上的输入是“hello world”:

您的意见是什么?
你好世界
你好世界
3 个字
1 个空间
11 个字符

【问题讨论】:

  • 你永远不会在你的 main 方法中调用你的 numberOfWords 函数。
  • 对不起,我是 java 新手。我不明白你的确切意思。您是说它不在 main 方法的括号内吗? @OHGODSPIDERS
  • 正如@OHGODSPIDERS 提到的,您需要在读取输入上调用该函数,例如String result = numberOfWords(input);
  • 输入“Hello World”三个字怎么样?

标签: java


【解决方案1】:

首先,为了能够得到函数numberOfWords的计算结果,你需要用你的输入调用它,见代码

接下来更喜欢Scanner而不是BufferedReader + InputStreamReader,语法更简单

public static void main(String argv[]) {

    Scanner sc = new Scanner(System.in);

    System.out.println("What is your input?");
    String input = sc.nextLine();                   // change to Scanner

    if (input.equals("exit")) {
        System.out.println("GOODBYE!");
    } else {
        System.out.println(input);
        System.out.println(numberOfWords(input));  // add method call
    }
}

我还提供了一种更简单的方法来实现你的东西:

public static String numberOfWords(String words) {
    int nbWord = words.split("\\s").length;
    int nbSpaces = nbWord - 1;
    return (nbWord + nbSpaces) + " words\n" + nbSpaces + " spaces\n" + words.length() + " characters";
}

words.split("\\s") 分割空格并创建一个单词数组,其长度为空格数

【讨论】:

    【解决方案2】:

    使用 split 并将结果分配给数组将使您能够获得所需的所有信息,如您所见,我首先 trim 因为我们假设只有单词之间的空白。

    words = words.trim();
          String tokens[] = words.split(" ");
    

    下面是使用此方法的工作示例:

     words = words.trim();
          String tokens[] = words.split(" ");
          int chars =0;
          int wordsN =0;
          int whitespace = 0;
          for(String s : tokens){
              chars+=s.length();
              wordsN++;       
          }
          whitespace = wordsN-1;
          chars += whitespace;
    
          System.out.println(chars);
          System.out.println(wordsN);
          System.out.println(whitespace);
    

    【讨论】:

      【解决方案3】:

      这里可以使用拆分功能

                  String input = "Hello World";
          String w[]=input.split(" ");
          int words=w.length;
          int l=input.length();
          System.out.println("characters "+l);
          System.out.println("words "+words);
          System.out.println("spaces "+(words-1));
      

      输出:字符 11 词 2 空格 1

      【讨论】:

      • 这不包括长度中的空格
      • 它包含空格,这就是答案为 11 的原因
      【解决方案4】:

      你永远不会在你的 main 方法中调用你的 numberOfWords 函数。

      试试这个:

      import java.io.BufferedReader;
      import java.io.IOException;
      import java.io.InputStreamReader;
      
      public class MyFirstProject {
      
        public static void main(String argv[]) throws IOException {
      
          //This line will create a buffered reader that reads from the system input using an input stream reader
          BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
          //input will contain the first line of input from the user   
          /**
           * This asks a question.
           */
          System.out.println("What is your input?");
          String input = bufferedReader.readLine();
          /**
           * This returns a valediction or the input.
           */
          if (input.equals("exit")) {
              System.out.println("GOODBYE!");
          }
          else {
              //****** HERE'S IS CHANGE! ********
              System.out.println(numberOfWords(input));
          }
      
      
          }
      
      
      /**
       * This counts the number of words (including spaces) in a string.
       * @param words The user input.
       * @return The number of words in a string.
       */
      public static String numberOfWords(String words) {
        int count = 0;
        if (words.length() == 1) {
            count++;
            return (String.valueOf(count) + "word");
        }
        if (words.length() > 1) {
            for (int i = 0; i <= words.length(); i++) {
                if (words.charAt(i) == ' ') {
                    count++;
                }
            }
            return (String.valueOf(count) + "words");
        }
        else {
            return (String.valueOf(count) + "words");
        }
      }
      }
      

      【讨论】:

      • 您能突出显示更改吗?那样会更容易被发现,尤其是对于初学者。
      • 哦,我明白了!谢谢!我没有得到我需要的输出,但我认为我可以使用它。再次感谢。
      • @Zabuza 在 main 的 else 语句中
      猜你喜欢
      • 1970-01-01
      • 2019-05-28
      • 2016-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-21
      相关资源
      最近更新 更多