2014-11-14 104 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

相关问题