简体   繁体   中英

How can you check user input validation in Java?

I'm making a simple program that asks the user to input five numbers between 0-19. I would like to add something (like an if statement) after every number to make sure it's within that range. If not, the program should say "please read instructions again" and will then System.exit(0). This is the piece of the code that is relevant:

System.out.println("Please enter 5 numbers between 0 and 19");
System.out.print("1st Number: ");
userNum1 = scan.nextInt();
System.out.print("2nd Number: ");
userNum2 = scan.nextInt();
System.out.print("3rd Number: ");
userNum3 = scan.nextInt();
System.out.print("4th Number: ");
userNum4 = scan.nextInt();
System.out.print("5th Number: ");
userNum5 = scan.nextInt();

Any help would be greatly appreciated.

You can put this after each of your inputs, but you might want to think about putting this logic into its own method, then you can reuse the code and just call it with something like validateInput(userNum1); .

Replace val with your actual variable names.

if (val < 0 || val > 19) {
    System.out.println("please read the instructions again");
    System.exit(0);
}

This code will do the trick for you, i added some securities :

public static void main(String[] args) {
    int count = 1;
    Scanner scan = new Scanner(System.in);
    List<Integer> myNumbers = new ArrayList<Integer>();
    System.out.println("Please enter 5 numbers between 0 and 19");
    do {
        System.out.println("Enter Number "+count+" ");
        if(scan.hasNextInt()){
            int input = scan.nextInt();
            if(input >= 0 && input <= 19){
                myNumbers.add(input);
                count++;
            }else{
                System.out.println("Please read instructions again");
                System.exit(0);
            }
        }else{
            scan.nextLine();
            System.out.println("Enter a valid Integer value");
        }
    }while(count < 6);

    /* NUMBERS */
    System.out.println("\n/** MY NUMBERS **/\n");
    for (Integer myNumber : myNumbers) {
        System.out.println(myNumber);
    }
}

Hope it helps

First of all, I would create a for-loop that iterates N times, with N being the number of numbers you want to ask for (in your case, 5). Imagine your example with 50 numbers; it would be very repetitive.

Then, when you get each number with scan.nextInt() within your for-loop, you can validate however you want:

if (userNum < 0 || userNum > 19) {
    // print error message, and quit here
}

Also, instead of just exiting when they input a number outside the range, you could have your logic inside a while loop so that it re-prompts them for the numbers. This way the user doesn't have to restart the application. Something like:

boolean runApplication = true;

while(runApplication) {
    // do your for-loop with user input scanning
}

Then set the runApplication flag as needed based on whether or not the user put in valid numbers.

Since you already know how many numbers you want the user to input, I suggest you use a for loop. It makes your code more elegant and you can add as many more entries as you want by changing the end condition of the loop. The only reason it looks long is because number 1, 2, 3 all end in a different format ie firST secoND thiRD, but the rest of the numbers all end with TH. This is why I had to implement some if else statements inside the loop.

To explain the code, every time it loops it first tells the user the count of the number he/she is entering. Then numEntry is updated every time the loop loops, therefore you do not need to assign multiple inputs to multiple variables. It is more efficient to update the same variable as you go on. If the input the user inputs is less than 0 OR it is more than 19, the system exits after an error message.

    System.out.println("Please enter a number between 0 and 19");
    Scanner scan = new Scanner(System.in);
    for(int i = 1; i <=5; i++){
    if(i == 1)
        System.out.println("1st Number");
    else if(i == 2)
        System.out.println("2nd Number");
    else if(i == 3)
        System.out.println("3rd Number");
    else
        System.out.println(i + "th Number");
    int numEntry = scan.nextInt();
    if(numEntry < 0 || numEntry > 19){
        System.out.println("Please read instructions again.");
        System.exit(1);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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