我想使用方法来计算一个句子中的单词数。我写了这段代码,但我不太确定它为什么不起作用。不管我写什么,我只收到一个字数。如果你能告诉我如何修复我写的东西,而不是给我一个完全不同的想法,那就太好了:
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.");
    }
}