当我尝试重复代码时出现此错误。
线程“main”中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:1 输入一个句子,这个程序会告诉你 有多少元音(不包括'y'): at 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 :(得分:0)
我认为您的错误来自您使用charAt() 当索引等于字符串的大小时抛出此异常。
答案 1 :(得分: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);