输入一行字符(少于300个字符),以回车结束,统计其中单词的个数。各单词之间用空格分隔,空格数可以是多个。用java解决
时间: 2024-06-14 22:04:19 浏览: 59
以下是使用Java解决输入一行字符统计单词个数的示例代码:
```java
import java.util.Scanner;
public class WordCount {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一行字符:");
String input = scanner.nextLine();
int count = countWords(input);
System.out.println("这个字符串有" + count + "个单词");
}
public static int countWords(String input) {
int count = 0;
boolean isWord = false;
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (Character.isLetter(c)) {
isWord = true;
} else if (isWord) {
count++;
isWord = false;
}
}
if (isWord) {
count++;
}
return count;
}
}
```
阅读全文