找不到符号-方法计数(java.lang.string)
我正在尝试制作一个不必使用split()的字数计算程序。 好吧,在你们告诉我这是复制品之前。我知道。 另一个解决方案对我来说不是很具体,因为他们使用add方法找不到符号-方法计数(java.lang.string),java,string,methods,count,lang,Java,String,Methods,Count,Lang,我正在尝试制作一个不必使用split()的字数计算程序。 好吧,在你们告诉我这是复制品之前。我知道。 另一个解决方案对我来说不是很具体,因为他们使用add方法 public static void findWord() { Scanner input = new Scanner(System.in); System.out.println("Enter a sentence"); String sentence = input.nextLine(); int n
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);
}
您需要一个
count
方法。这是一个简单的例子:
public int count(String sentence) {
return sentense.split(" ").length;
}
sentense.split(“”
将在有空格的地方拆分句子
,并返回字符串数组
(“hello world”
变为{“hello”,“world”}
)
.length
将返回数组中的项数,在本例中为字数。如Stefan所述,您缺少一个count
方法(这是您在说count(句子);
时试图调用的方法)
此处的回答略有不同,因为您要求不要使用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());