我想写一个代码,要求用户输入他们的名字,将它存储在列表中,然后要求他们输入他们的年龄,将它存储在另一个列表中。然后询问用户是否想再次尝试[是/否]。 当测试代码时,我输入“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”作为年龄。 –