【问题标题】:count words of sentences?计算句子的单词?
【发布时间】:2018-01-21 17:42:30
【问题描述】:

我想计算每个句子的单词数我写的代码但是计算句子中每个单词的字符这是我的代码

public static void main(String [] args){
    Scanner sca = new Scanner(System.in);
    System.out.println("Please type some words, then press enter: ");
    String sentences= sca.nextLine();
    String []count_words= sentences.split(" ");
    for(String count : count_words){
    System.out.println("number of word is "+count.length());}
}

【问题讨论】:

标签: java arrays java-6


【解决方案1】:

方法调用count.length() 正在返回每个单词的长度,因为循环将每个单词分配给变量count。 (这个变量名很混乱。)

如果要句子中的单词个数,则需要count_words数组的大小,即count_words.length

【讨论】:

    【解决方案2】:

    String[] count_words= sentences.split(" "); 将输入参数除以" ",这意味着这个数组的长度是单词的数量。只需将长度打印出来。

    public static void main(String[] args) {
        Scanner sca = new Scanner(System.in);
        System.out.println("Please type some words, then press enter: ");
        String sentences= sca.nextLine();
        String[] count_words= sentences.split(" ");
        System.out.println("number of word is "+ count_words.length);
    }
    

    示例:

    oliverkoo@olivers-MacBook-Pro ~/Desktop/untitled folder $ java Main
    Please type some words, then press enter: 
    my name is oliver
    number of word is 4
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多