[英]Java: For loop not printing the last iteration
我目前正在嘗試制作一個簡單的程序,該程序將計算多個句子中的元音數量。 輸入看起來像這樣:
6
艾米麗跳得很高
亞歷克斯沒有跳
菲利普討厭跳
紅龍會飛
三明治很好
我喜歡太陽
該數字指示有多少行。 我的問題是,當我打印出結果時,最后一行會被忽略。 因此,該程序打印出5個整數,而不是6個整數。我使用它已有很長時間了,但似乎無法解決這個問題。
Scanner in = new Scanner(System.in);
int cases = in.nextInt(); //how many lines there are
String a;
int vowels = 0;
int length; //length of a line
char temp;
in.nextLine(); //skips first line of the input, as this declares how many lines there are
for (int i = 0; i <= cases; i++)
{
a = in.nextLine();
length = a.length();
//System.out.println(a);
for (int b = 0; b < length; b++)
{
temp = a.charAt(b);
if (temp == 'a' || temp == 'e' || temp == 'i' || temp == 'o' || temp == 'u')
{
vowels++;
}
}
System.out.println(vowels);
vowels=0;
}
出於某種原因,當我發布輸入內容時,它會自動向我顯示前5個整數,然后我只需要按Enter即可顯示最后一個整數。 所以顯然打回車現在也是我獲得的技能之一;)
您有額外的循環步驟:
for (int i = 0; i <= cases; i++)
您需要的循環是:
for (int i = 0; i < cases; i++)
您正在為案例循環1次,即7次。 你應該使用
for (int i = 0; i < cases; i++)
要么
for (int i = 1; i <= cases; i++)
否則,您的代碼將輸出預期的輸出。
您的代碼工作正常。 您只需要將i < case
i <= case
更改為i < case
一個問題。 您可以使用該網站通過std輸入測試您的代碼。 https://ideone.com/Ud3MWt
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.