我应该使用方法来计算句子中的单词数。我写了这段代码,但我不太确定为什么它不起作用。无论我写什么,我只收到 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();
use in.nextLine()
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)