Java初学者-计算句子中的单词数 [英] Java Beginner - Counting number of words in sentence
本文介绍了Java初学者-计算句子中的单词数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用一些方法来计算一个句子中的单词数.我写了这段代码,但我不太确定为什么它不起作用.无论我写什么,我都只会收到一个单词的数.如果您能告诉我如何修正我写的内容,而不是给我一个完全不同的主意,那就太好了:
I am suppose to use methods in order to count number of words in the a sentence. I wrote this code and I am not quite sure why it doesn't work. No matter what I write, I only receive a count of 1 word. If you could tell me how to fix what I wrote rather than give me a completely different idea that would be great:
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()
.
You need to read entire line. Instead of in.next();
use in.nextLine()
.
这篇关于Java初学者-计算句子中的单词数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文