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

标签 java methods

我想使用方法来计算句子中的单词数。我写了这段代码,但我不太确定为什么它不起作用。无论我写什么,我只收到 1 个字的计数。如果你能告诉我如何修复我写的东西而不是给我一个完全不同的想法,那就太好了:

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.");
    }
}

最佳答案

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

关于Java初学者 - 计算句子中的单词数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15930946/

相关文章:

java - swing 中的 JTable 可点击标题

java - 创建的方法,在返回其中的变量时遇到问题

java.lang.ClassNotFoundException : javax. servlet.jsp.tagext.Tag

java - Spring jpa使用自定义Query时抛出ClassCastException

java - Java 中 10,000 以下的数字之和是 3、5 或 7 的倍数

python - 多处理Python中的self

java - 主方法中的打印方法不起作用 - Java

java - 从 Java 调用 JavaScript 方法

java - 删除在第一个索引处停止的索引方法(java字符串数组)

java - 以编程方式配置记录器