Java初学者 - 计算句子中的单词数

use*_*957 4 java methods

我想使用方法来计算句子中的单词数量.我写了这段代码,我不太清楚为什么它不起作用.无论我写什么,我只收到一个字数.如果你能告诉我如何解决我写的东西,而不是给我一个完全不同的想法,那将是伟大的:

import java.util.Scanner;

public class P5_7 
{
    public static int countWords(String str)
    {
        int count = 1;
        for (int i=0;i<=str.length()-1;i++)
        {
            if (str.charAt(i) == ' ' && str.charAt(i+1)!=' ')
            {
                count++;
            }
        }
        return count;
    }
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a sentence: ");
        String sentence = in.next();
        System.out.print("Your sentence has " + countWords(sentence) + " words.");
    }
}
Run Code Online (Sandbox Code Playgroud)

Psh*_*emo 5

您需要阅读整行。代替in.next();使用in.nextLine()


Ósc*_*pez 5

解决此问题的简便方法:

return str.split(" ").length;
Run Code Online (Sandbox Code Playgroud)

或者更加小心,这就是你如何考虑多个空白:

return str.split("\\s+").length;
Run Code Online (Sandbox Code Playgroud)