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"の場合、出力は次のようになります。単語(スペースを含む)を数えるには?
入力は何ですか?
Hello Worldの
のHello World
3ワード
1スペース
11文字
あなたはあなたの主な方法であなたの 'numberOfWords'関数を呼び出すことはありません。 –
ここをクリックhttps://stackoverflow.com/questions/5864159/count-words-in-a-string-method –
申し訳ありませんが、私はjavaを初めて使いました。私はあなたが正確に何を意味するのか理解していません。あなたはそれが主要な方法の括弧内にないと言っていますか? @OHGODSPIDERS – suuugarpie