当用户输入重复代码时,出现错误
问题描述:
当我尝试重复代码时,出现此错误。螺纹当用户输入重复代码时,出现错误
异常“主要” 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");
}
}
答
我怀疑你得到这个例外,当你有一个单词只包含单个字符。为了消除这一点,并且也提升你的代码,我将取代这一行:
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);
当您通过本在调试步骤,是什么导致错误的字符串的运行时间值? – David 2014-11-14 16:04:40