【发布时间】:2018-03-04 05:25:26
【问题描述】:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class MyFirstProject {
public static void main(String argv[]) throws IOException {
//This line will create a buffered reader that reads from the system input using an input stream reader
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
//input will contain the first line of input from the user
/**
* This asks a question.
*/
System.out.println("What is your input?");
String input = bufferedReader.readLine();
/**
* This returns a valediction or the input.
*/
if (input.equals("exit")) {
System.out.println("GOODBYE!");
}
else {
System.out.println(input);
}
}
/**
* This counts the number of words (including spaces) in a string.
* @param words The user input.
* @return The number of words in a string.
*/
public static String numberOfWords(String words) {
int count = 0;
if (words.length() == 1) {
count++;
return (String.valueOf(count) + "word");
}
if (words.length() > 1) {
for (int i = 0; i <= words.length(); i++) {
if (words.charAt(i) == ' ') {
count++;
}
}
return (String.valueOf(count) + "words");
}
else {
return (String.valueOf(count) + "words");
}
}
}
我的问题很简单。我很难理解为什么我的代码不会返回输入中的单词数。输出应该是这样的,例如,如果用户在控制台上的输入是“hello world”:
您的意见是什么?
你好世界
你好世界
3 个字
1 个空间
11 个字符
【问题讨论】:
-
你永远不会在你的 main 方法中调用你的
numberOfWords函数。 -
对不起,我是 java 新手。我不明白你的确切意思。您是说它不在 main 方法的括号内吗? @OHGODSPIDERS
-
正如@OHGODSPIDERS 提到的,您需要在读取输入上调用该函数,例如
String result = numberOfWords(input);。 -
输入“Hello World”三个字怎么样?
标签: java