Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/366.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用while循环和扫描仪验证输入_Java_Input_While Loop_Java.util.scanner_Validating - Fatal编程技术网

Java 使用while循环和扫描仪验证输入

Java 使用while循环和扫描仪验证输入,java,input,while-loop,java.util.scanner,validating,Java,Input,While Loop,Java.util.scanner,Validating,从指定范围(0,20)且为int的用户处获取有效整数的最佳方法是什么。如果他们输入了无效的整数,打印输出错误 我的想法是: int choice = -1; while(!scanner.hasNextInt() || choice < 0 || choice > 20) { System.out.println("Error"); scanner.next(); //clear the buffer } choice = scanner.next

从指定范围(0,20)且为
int
的用户处获取有效整数的最佳方法是什么。如果他们输入了无效的整数,打印输出错误

我的想法是:

 int choice = -1;
 while(!scanner.hasNextInt() || choice < 0 || choice > 20) {
       System.out.println("Error");
       scanner.next(); //clear the buffer
 }
 choice = scanner.nextInt();
int-choice=-1;
而(!scanner.hasNextInt()| | choice<0 | | choice>20){
System.out.println(“错误”);
scanner.next();//清除缓冲区
}
选项=scanner.nextInt();

这是正确的还是有更好的方法?

您可以这样做:

Scanner sc = new Scanner(System.in);
int number;
do {
    System.out.println("Please enter a valid number: ");
    while (!sc.hasNextInt()) {
       System.out.println("Error. Please enter a valid number: ");
       sc.next(); 
    }
    number = sc.nextInt();
} while (!checkChoice(number));

private static boolean checkChoice(int choice){
    if (choice <MIN || choice > MAX) {     //Where MIN = 0 and MAX = 20
        System.out.print("Error. ");
        return false;
    }
    return true;
}
Scanner sc=新扫描仪(System.in);
整数;
做{
System.out.println(“请输入有效数字:”);
而(!sc.hasnetint()){
System.out.println(“错误。请输入有效数字:”);
sc.next();
}
编号=sc.nextInt();
}而(!checkChoice(number));
私有静态布尔checkChoice(int-choice){
如果(选择最大值){//其中最小值=0,最大值=20
系统输出打印(“错误”);
返回false;
}
返回true;
}
此程序将不断请求输入,直到获得有效输入


确保您了解程序的每个步骤。

在while循环中,您在哪里更改选择?如果未更改,则不能期望在If块的布尔条件中使用它

您必须检查扫描仪是否没有int,如果有int,请选择并单独检查

伪代码:

set choice to -1
while choice still -1
  check if scanner has int available
    if so, get next int from scanner and put into temp value
    check temp value in bounds
    if so, set choice else error
  else error message and get next scanner token and discard
done while

这段代码是否符合您的期望?如果是,那么你的问题是什么,如果不是,那么错误是什么?即使我输入了一个在范围内的数字,它也会一直打印出错误我只是尝试了一下,如果第一次选择的不是整数,它会抛出一个InputMismatheException。