2017-10-10 105 views
2

我在我的大學入門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」任何幫助,將不勝感激。

+0

現在是瞭解如何使用調試器的好時機。變量「空間」的價值是什麼? – OldProgrammer

+0

'space'的值永遠不會更新 –

回答

0

嘗試用:

int len = userInput.split(" ")[0].length(); 

這會給你用空白分裂字的數組,然後就拿到陣列的第一位置,並最終得到了長度。

+0

非常感謝您的回答。不幸的是我不能使用數組,因爲我們還沒有在課堂上講過它們。 –

0
userInput.indexOf(" "); 

這給出了不使用數組的第一個單詞的長度。

的的StringIndexOutOfBoundsException拋出因爲,由於space從不更新,代碼結束了從具有2長度的字符串試圖字符串索引0至4。

如果userInput在while循環印刷,輸出將是:

This is a sentence 
is a sentence 
a sentence 
ntence 
ce 

然後StringIndexOutOfBounds被拋出。

我會數從句子的每一個字,而無需使用陣列的方法是:

Scanner in = new Scanner(System.in); 

System.out.print("Enter a sentence: "); 
String input = in.nextLine(); 
in.close(); 

int wordCount = 0; 

while (input.length() > 0) { 
    wordCount++; 
    int space = input.indexOf(" "); 
    if (space == -1) { //Tests if there is no space left 
     break; 
    } 
    input = input.substring(space + 1, input.length()); 
} 

System.out.println("The number of word entered is: " + wordCount); 
+0

非常感謝你的回答。我現在明白了這個問題,我只是不知道如何解決它。我認爲問題出在'userInput = userInput.substring(space);'這是應該讓它進入下一個單詞和句子的其餘部分,但我錯了。 –

+0

請參閱編輯anwser ... –

0

你的問題是,你還沒有被更新的空間和字母。 看到下面你的代碼與我應該工作正常的小改動。

Scanner myScanner = new Scanner(System.in); 

     int letters = 1; 

     int wordCount1 = 1; 
     String firstWord = null; 

     System.out.print("Enter a sentence: "); 
     String userInput = myScanner.nextLine(); 


     int space = -2; //= userInput.indexOf(" "); // integer for a space character 

     while (letters <= userInput.length() && space != -1) { 

     space = userInput.indexOf(" "); 
     if (space != -1) 
      firstWord = userInput.substring(0, space); 
     if (firstWord.length() == 1) 
      wordCount1 = 1; 
     userInput = userInput.substring(space + 1); 
     } 
     System.out.print(wordCount1); 
} 
相關問題