【问题标题】:Cannot find symbol - method count(java.lang.string)找不到符号 - 方法计数(java.lang.string)
【发布时间】:2017-10-24 15:19:13
【问题描述】:

我试图制作一个字数统计程序而不必使用 split()。 好的,在你们告诉我说这是重复之前。我知道。 另一个解决方案对我来说不是很具体,因为他们使用的是 add 方法。

public static void findWord()
{
    Scanner input = new Scanner(System.in);

    System.out.println("Enter a sentence");
    String sentence = input.nextLine();
    int numOfWords = count(sentence);

这里计数出现错误。

    System.out.println("input: " + sentence);
    System.out.println("number of words: " + numOfWords);
}

【问题讨论】:

标签: java string methods count lang


【解决方案1】:

正如 Stefan 提到的,您缺少 count 方法(因为这是您在说 count(sentence); 时试图调用的方法)

这里的答案略有不同,因为您要求不要使用split()

public static int count(String s) {
        int count = 1; //to include the first word
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == ' ') {
                count++;
            }
        }
        return count;
    }

如果空格是个问题,更好的方法是:

StringTokenizer st = new StringTokenizer(sentence);
System.out.println(st.countTokens());

【讨论】:

    【解决方案2】:

    您需要一个count 方法。这是一个简单的例子:

    public int count(String sentence) {
        return sentense.split(" ").length;
    }
    

    sentense.split(" ") 将分割有空格的sentence,并返回Strings 的数组("hello world" 变为{"hello", "world"})。

    .length 将返回数组中的项目数,在本例中为单词数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-24
      • 2011-08-12
      • 1970-01-01
      • 1970-01-01
      • 2015-01-19
      • 1970-01-01
      • 1970-01-01
      • 2019-05-31
      相关资源
      最近更新 更多