Scanner sc = new Scanner(System.in );
int number;
while(true) {
if(sc.hasNextInt()) {
number = sc.nextInt();
break;
}
else {
sc.next();//取出来调用sc对象的方法取数
System.out.println("输入错误");
}
}
在上面的代码中sc.next();这个东西一开始不知该如何去理解,去掉这个语句就会陷入死循环;为什么呢?这是因为之前number = sc.nextInt();已经接收了输入,已经有了值,必须将其清掉拿走才会中断这个循环;
sc.next();起到一个等待下一个输入数的状态的作用从而中断循环;我个人的理解