我在我的大學入門Java課程。對於我的任務,我必須編寫一個程序來顯示一個句子中的1個字母單詞的數量,一個句子中的2個字母單詞的數量等。該句子是用戶輸入的。我應該使用循環,我不允許使用數組。計算句子第一個單詞中的字母數
但是現在剛開始,我只是試圖找出句子第一個單詞中的字母數。我給了我一個不正確的字母計數或一個錯誤,指出字符串索引超出範圍。
Scanner myScanner = new Scanner(System.in);
int letters = 1;
int wordCount1 = 1;
System.out.print("Enter a sentence: ");
String userInput = myScanner.nextLine();
int space = userInput.indexOf(" "); // integer for a space character
while (letters <= userInput.length()) {
String firstWord = userInput.substring(0, space);
if (firstWord.length() == 1)
wordCount1 = 1;
int nextSpace = space;
userInput = userInput.substring(space);
}
System.out.print(wordCount1);
例如,當我輸入「這是一句」它給了我「字符串索引超出範圍:4」任何幫助,將不勝感激。
現在是瞭解如何使用調試器的好時機。變量「空間」的價值是什麼? – OldProgrammer
'space'的值永遠不會更新 –