Java 为什么这段代码不等待输入
我希望代码停止并再次等待输入,但它的运行就像用户每次按enter键一样,创建了一个无限循环Java 为什么这段代码不等待输入,java,loops,input,Java,Loops,Input,我希望代码停止并再次等待输入,但它的运行就像用户每次按enter键一样,创建了一个无限循环 while(asking) { try { int answer = input.nextInt(); } catch(Exception InputMismatchException) { System.out.println("Please only enter numbers."); } } 为什么会这样 编辑:我不担心
while(asking) {
try {
int answer = input.nextInt();
}
catch(Exception InputMismatchException) {
System.out.println("Please only enter numbers.");
}
}
为什么会这样
编辑:我不担心退出while循环。问题是它不会等待输入
EDIT2:如果没有触发异常,它将按预期运行。(即用户输入了一个整数限制内的数字)在
循环时,您不能更改内的询问的值,因此它将是一个无限循环。试试这个。nextInt没有阻塞。nextLine有
while(asking) {
try {
int answer = input.nextInt();
}
catch(Exception InputMismatchException) {
System.out.println("Please only enter numbers.");
}
}
while(asking) {
int answer;
try {
answer = Integer.parseInt(input.nextLine());
}
catch(Exception NumberFormatException) {
System.out.println("Please only enter numbers.");
}
}
我认为这会奏效:
while(asking) {
try {
int answer = input.nextInt();
}
catch(Exception InputMismatchException) {
System.out.println("Please only enter numbers.");
input.next();
}
}
您需要调用nextLine
,以防收到执行选项。否则它会创建一个无限循环。哪个值有询问,它什么时候会改变?你在哪里设置询问?@EduardoYáñezParareda无所谓,将其设置为true,永远不要改变它问题会重现。