【发布时间】:2013-04-10 16:06:01
【问题描述】:
我想使用方法来计算句子中的单词数。我写了这段代码,但我不太确定它为什么不起作用。不管我写什么,我只收到一个字的计数。如果你能告诉我如何修正我写的东西,而不是给我一个完全不同的想法,那就太好了:
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.");
}
}
【问题讨论】:
-
怎么不工作了?是否有异常,或者只是输出不正确?
-
在什么情况下不起作用?你能提供输入和输出的例子吗?
-
您没有考虑极端情况,例如:字符串为空;结尾有空格;字符串为 NULL。单词分隔符也是“空白”,包括制表符、行尾等。您的算法还假设字符串中至少有一个单词。
-
不管我最后只得到 1 个字。我只是一个初学者,所以所有这些例外都相对无关