简体   繁体   English

使用Java扫描器在接受用户输入时检查两个条件

[英]Using java scanner to check two conditions while taking user input

I need to user to enter an int between 1 and 301. I have this simple loop here to check for user input. 我需要用户输入一个介于1和301之间的整数。我这里有一个简单的循环来检查用户输入。 I just want a single number from the user, and if the user enters anything other than an int between 1 and 301, I want to display the print line and prompt the users to try again until they enter a valid input. 我只是想从用户的单一号码,如果用户输入比1和301之间的一个int以外的任何其他,我想要显示的打印线,并提示用户,直到他们进入一个有效的输入再试一次。

        while (!sc.hasNextInt()) {
            System.out.print("Invalid Input. Please enter a valid number between 1 and 301: ");
            sc.next();
        }
        int numToCheck = sc.nextInt();
        // do stuff with numToCheck

This checks that the input is an int, but I can't seem to find a way to give the int input a bound. 这将检查输入是否为int,但是我似乎找不到找到给int输入一个界限的方法。 I tried to assign the user input to a variable and then check the conditions input < 1 or input > 301, but I get InputMismatchException if user enters a letter. 我尝试将用户输入分配给变量,然后检查条件输入<1或输入> 301,但是如果用户输入字母,则会收到InputMismatchException。 How should I store the user input? 我应该如何存储用户输入? (I want to store it as an int to check the conditions, but can't do that since I don't know what the user will enter). (我想将其存储为一个int来检查条件,但由于不知道用户将输入什么,所以不能这样做)。

Perhaps there is a better design to accomplish all this. 也许有一个更好的设计可以完成所有这一切。 Those are welcomed too. 这些也受到欢迎。

Thanks in advance. 提前致谢。

You're not saving the value of the of the input. 您没有保存输入的的值。 So your program is waiting on the user to enter a number each time it see "sc.nextInt()" Assign the input to a variable, and then check the condition. 因此,您的程序每次看到"sc.nextInt()"时都在等待用户输入数字,将输入分配给变量,然后检查条件。 EDIT: okay, I'll go the extra mile for you. 编辑:好的,我会为您付出更多的努力。 See if this works. 看看是否可行。

***Accounted for the case where the user might enter a character instead of a number. ***说明了用户可能输入字符而不是数字的情况。

import java.util.*;
public class HelloWorld{

public static void main(String []args){
    Scanner sc = new Scanner(System.in);
    int input;
    while (true){
        if (sc.hasNextInt()){
             input = sc.nextInt(); // Assign the next integer to a variable
             if (input  <= 301  && input >= 1){ // Check if integer meets condition
                   break; // Condition met, break out of loop
            }
        }else{
              sc.next();
        }
        System.out.println("Invalid Input. Please enter a valid number between 1 and 301: ");
    }
}

} }

Assuming you want only 1 input from the user, try following simple code, which takes input from the user until user enters a valid input. 假设您只需要用户输入1次,请尝试遵循以下简单代码,该代码将接受用户输入,直到用户输入有效输入为止。

Scanner in = new Scanner(System.in);
     int flag = 0,x=0;
     while(flag == 0){
         x = in.nextInt();
         if(x<1 || x>301){
             flag = 0;
             System.out.println("Invalid Input.");
         }
         else{
             flag = 1;
         }
     }

And if you want user to input more than 1 inputs (ie 3 here), than set a counter that increases with every valid input of the user, as following: 并且,如果您希望用户输入多个输入(即此处为3个),则应设置一个随用户的每个有效输入而增加的计数器,如下所示:

 Scanner in = new Scanner(System.in);
     int flag = 0,x=0,count = 1;
     while(flag == 0){
         x = in.nextInt();
         if(x<1 || x>301){
             flag = 0;
             System.out.println("Invalid Input.");
         }
         else{
             //executes when input is valid
             if(count == 3){
                 flag = 1;
             }
             count++;

         }
     }

Edit: 编辑:

If you also want to check whether the input is Integer or not, than you have to add one extra condition in above code. 如果还想检查输入是否为Integer ,则必须在上面的代码中添加一个附加条件。 And as you said you want only one input from user rather than 3 , you have to change exit condition. 正如您所说的,您只需要用户输入一次而不是3输入,您必须更改退出条件。 Change code as following: 更改代码如下:

Scanner in = new Scanner(System.in);
 int flag = 0,count = 1,x=0,flag1 = 0;
 String y;
 while(flag == 0){
     y = in.next();
     flag1 = 0;
     try{
         x = Integer.parseInt(y);
     }
     catch(NumberFormatException e){
         flag1 = 1;
         System.out.println("Invalid Input.");
     }
     if((x<1 || x>301)&&flag1 == 0){
         flag = 0;
         System.out.println("Invalid Input.");
     }
     else if(flag1 == 0){
         //executes when input is valid
         if(count == 1){   // put count == 3 if you want 3 inputs from user.
             flag = 1;
         }
         count++;
     }
 }

Here we are taking the input as a String and than converting the String into the Integer by using Integer.parseInt() . 在这里,我们将输入作为String而不是通过使用Integer.parseInt()String转换为Integer If the String is not Integer , than it will throw the exception and we will continue the loop till the valid input is entered by the user. 如果String不是Integer ,则它将引发异常,我们将继续循环直到用户输入有效输入为止。

I ran this code, to see if it would show a better performance than yours. 我运行了这段代码,以查看它是否会显示出比您更好的性能。

Scanner sc = new Scanner(System.in);

boolean valid = true;
do {
    if (!valid) {
        System.out.print("Invalid Input. ");
    }
    System.out.print("Please enter a valid number between 1 and 301: ");
    String input = sc.next();
    try {
        int value = Integer.parseInt(input);
        valid = (value >= 1 && value <= 301);
    } catch (NumberFormatException nfex) {
        valid = false;
    }
} while (!valid);

When the conversion to integer fails, the JVM hangs a little. 当转换为整数失败时,JVM会挂起一点。 I believe your problem has more to do with the try / catch mecanism that Scanner performs under the hood, than with design. 我相信您的问题更多与Scanner在幕后执行的“尝试/捕获”机制有关,而不是与设计有关。

Use DO WHILE for result 使用WHILE作为结果

  do{
     System.out.print("value of x : " + x );
     x++;
     System.out.print("\n");
  }while( x < 20 );

OK ? 好 ?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM