我想知道为什么第一个代码会陷入无限循环而第二个代码却能正常工作吗?!
第一个密码
public static void main(String[] args) {
boolean flag=true;
int age = 0 ;
while(flag){
try {
System.out.println("Enter your age = ");
age = scanner.nextInt();
flag=false;
}catch (Exception e){
System.out.println("Please enter a valid number");
}
}
System.out.println(" Your age is "+age);
}
第二个密码
public static void main(String[] args) {
boolean flag=true;
int age = 0 ;
while(flag){
try {
System.out.println("Enter your age = ");
String str=scanner.nextLine();
age =Integer.parseInt(str);
flag=false;
}catch (Exception e){
System.out.println("Please enter a valid number");
}
}
System.out.println(" Your age is "+age);
}