即使當我走到我的字符串的末尾,我的代碼也不會退出我的外部for循環,我無法弄清楚原因。根據我的理解,我的外循環應該在第四次迭代之後停止。相反,它繼續,然後錯誤在字符串inputString = input.next();因爲那裏什麼都沒有。這裏是我的代碼:代碼不會退出循環外部
public class Exercise17 {
public static void main(String[] args) {
String string = "i think, therefore i am";
vowelCount(string);
}
public static void vowelCount(String s) {
Scanner input = new Scanner(s);
int[] vowelArray = new int[5];
int aCount = 0, eCount = 0, iCount = 0, oCount = 0, uCount = 0;
for(int i = 0; i < s.trim().length() - 1; i++) {
String inputString = input.next();
System.out.println(inputString);
for(int j = 0; j < inputString.length(); j++) {
char c = inputString.charAt(j);
System.out.println(c);
if(c == 'a') {
aCount++;
}else if (c == 'e') {
eCount++;
}else if (c == 'i') {
iCount++;
}else if (c == 'o') {
oCount++;
}else if (c == 'u') {
uCount++;
}
}
}
vowelArray[0] = aCount;
vowelArray[1] = eCount;
vowelArray[2] = iCount;
vowelArray[3] = oCount;
vowelArray[4] = uCount;
input.close();
System.out.println(Arrays.toString(vowelArray));
}
}
正如我曾試圖擺脫-1並使它只是我< s.trim實驗()長(),以及將其更改爲我<秒。。 trim()。length()-2,i < s.trim()。length()-3,i < s.trim()。length()-4等,一直到-10。
爲什麼使用for循環而不是'input.hasNext()'? – azurefrog 2014-10-06 19:01:37
@azurefrog我懇求暫時的瘋狂。 – comfortablyNumb 2014-10-06 19:03:51