[英]Endless java loop while taking an input
我在這里的while循環中遇到這個問題:
while((input = InputHandler.getInt()) != 1 && input != 2){
if(input == InputHandler.CODE_ERROR)
System.out.print("Input must be a number");
}
該while循環僅接受一次輸入,並且不會再次請求輸入,因此它將在整個時間內對輸入進行循環。 我在這里做錯什么,因為對於我來說,這個循環循環正在起作用真的很奇怪嗎?
InputHandler類:
public class InputHandler {
public static Scanner in = new Scanner(System.in);
public static int CODE_ERROR = -6;
public static int getInt(){
try{
return in.nextInt();
} catch(InputMismatchException e){
return CODE_ERROR;
}
}
}
當前,如果在命令行中輸入非整數,則您的代碼將進入無限循環。 這是因為您的in.nextInt()
方法引發了異常,並將有問題的值留在了掃描器中 。
您需要通過調用in.next();
來消耗導致您的異常的無效令牌in.next();
:
public static void main(String[] args) throws Exception {
int input;
while ((input = InputHandler.getInt()) != 1 && input != 2) {
if (input == InputHandler.CODE_ERROR)
System.out.print("Input must be a number");
}
}
public static class InputHandler {
public static Scanner in = new Scanner(System.in);
public static int CODE_ERROR = -6;
public static int getInt(){
try{
return in.nextInt();
} catch(InputMismatchException e){
in.next(); // <------------------ this should solve it
return CODE_ERROR;
}
}
}
我運行的代碼運行正常,每次輸入2或1循環終止時都要求輸入。 這是我運行的代碼示例:-
package testing;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Test123 {
public static Scanner in = new Scanner(System.in);
public static int CODE_ERROR = -6;
public static int getInt(){
try{
String in1 = in.next();
return Integer.parseInt(in1);
//return in.nextInt(); <-- This is leading to error
} catch(Exception e){
return CODE_ERROR;
}
}
public static void main(String[] args) {
int input;
while((input = Test123.getInt()) != 1 && input != 2){
if(input == Test123.CODE_ERROR)
System.out.print("Input must be a number");
System.out.println("\nWrong number: "+input+" Please try again.");
//input = Test123.getInt();
}
}
}
我不明白你為什么要面對問題?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.