我想寫一個代碼,要求用戶輸入他們的名字,將它存儲在列表中,然後要求他們輸入他們的年齡,將它存儲在另一個列表中。然後詢問用戶是否想再次嘗試[是/否]。 當測試代碼時,我輸入「Y」,並期望循環要求我輸入另一個名稱。相反,它跳過名稱輸入並跳轉到年齡輸入。我無法弄清楚爲什麼。 代碼如下爲什麼此循環的第二次迭代會跳過第一次掃描?
import java.util.ArrayList;
import java.util.Scanner;
public class PatternDemoPlus {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
ArrayList<String> names = new ArrayList<String>();
ArrayList<Integer> ages = new ArrayList<Integer>();
String repeat = "Y";
while(repeat.equalsIgnoreCase("Y")){
System.out.print("Enter the name: ");
names.add(scan.nextLine());
System.out.print("Enter the age: ");
ages.add(scan.nextInt());
System.out.print("Would you like to try again? [Y/N]");
repeat = scan.next();
//Notice here that if I use "repeat = scan.nextLine(); instead, the code does not allow me to input anything and it would get stuck at "Would you like to try again? [Y/N]
System.out.println(repeat);
//Why is it that after the first iteration, it skips names.add and jumps right to ages.add?
}
}
}
我希望得到您的幫助。謝謝。
提示:您是否檢查過在'repeat = scan.next()'這一行收到的內容?注意輸入「123 XYZ」作爲年齡。 –