2014-11-14 42 views
0

當我嘗試重複代碼時,出現此錯誤。螺紋當用戶輸入重複代碼時,出現錯誤

異常「主要」 java.lang.StringIndexOutOfBoundsException:字符串索引超出範圍:1種 類型的句子,並將該軟件會告訴你 多少元音也有(不包括「Y」): 是java。 lang.String.substring(String.java:1934) 在countvowels.Main.main(Main.java:53) Java結果:1

這裏是我的代碼:

Scanner input = new Scanner(System.in); 
    int answer = 0; 
    System.out.println("Count Vowels \n============"); 

    // the do-while loop makes sure that the code is executed at least once 
do { 
     if(answer == 1) { 
      System.out.println("You have chosen to count the vowels in another phrase"); 
     } 

     System.out.println("Type a sentence and this program will tell you\nhow many vowels there  are (excluding 'y'):"); 
     String string1; 

     string1 = input.nextLine(); 
     string1 = string1.toLowerCase(); 

     int vowels=0; 
     int i = 0; 

     for (String Vowels : string1.split(" ")) { 
      for (i = 0; i < Vowels.length(); i++) { 

       int letter = Vowels.charAt(i); 
       if (letter == 'a' || letter == 'e' || letter == 'i' 
         || letter == 'o' || letter == 'u') { 
        vowels++; 
       } 
      } 
      System.out.println(Vowels.substring(0,1) 
        + Vowels.substring(1) + " has " + vowels + " vowels"); 
      vowels = 0; 
     } 

    System.out.println("Would you like to check another phrase in the Vowel Counter? if so Press 1   if not press 2"); 

} while(input.nextInt() == 1); 


System.out.println("Have a nice day"); 
} 

} 
+0

當您通過本在調試步驟,是什麼導致錯誤的字符串的運行時間值? – David 2014-11-14 16:04:40

回答

0

我懷疑你得到這個例外,當你有一個單詞只包含單個字符。爲了消除這一點,並且也提升你的代碼,我將取代這一行:

System.out.println(Vowels.substring(0,1) + Vowels.substring(1) + " has " + vowels + " vowels"); 

有:

System.out.println(Vowels + " has " + vowels + " vowels"); 

另外,修改與以下停止循環:

nextInt() ,只讀取下一個整數值。因此,斷路器停留在緩衝區中,稍後由nextLine()命令處理。

修改環路具有以下結尾:

answer = input.nextInt(); 
    input.nextLine(); 
} 
while (answer == 1); 
+0

謝謝!但是,當我按1作爲用戶輸入時,它不會要求他們提供新的短語,它會直接說「有0個元音」,你願意再試一次嗎? – dappers 2014-11-14 16:28:14

+0

查看我的修改回答 – Amr 2014-11-14 16:47:06

+0

它的工作原理!非常感謝 – dappers 2014-11-14 17:26:52

0

我想你錯誤來自您使用charAt() 索引等於字符串大小時引發此異常。

+1

你有什麼建議我解決這個問題? – dappers 2014-11-14 16:09:58

相關問題