简体   繁体   中英

How can I validate user input in Java

I am currently experimenting with Java, trying to get the user to input an integer. If the user doesn't enter an integer I want a message to appear saying "You need to enter an Integer: " with a completely new input field to the original one.

Code:

import java.util.Scanner;

public class Test {

    public static void main(String[] args) {
    
        Scanner inputScanner = new Scanner(System.in);
        
        int counter = 0;
    
        boolean run = true;
        
        int userInput = 0;
        
        while (run) {
        
            System.out.print("Enter an integer: ");
            
            if (inputScanner.hasNextInt()) {
            
                userInput = inputScanner.nextInt();
            
            } else if (!inputScanner.hasNextInt()) {
                while (!inputScanner.hasNextInt()) {
                
                    System.out.print("You need to enter an Integer: ");
                    userInput = inputScanner.nextInt();
                
                }
            
            }
            
            System.out.println(userInput);
            
            if (counter == 6) {
            
                run = false;
            
            }
            counter++;
        
        }
    
    }

}

At the moment the code above gives an Exception error ("java.util.InputMismatchException"). I have tried to use a try/catch but this doesn't really work because I want the user to see the second message ("You need to enter an Integer") everytime they don't enter an integer and I don't want it to re-loop around the main run loop for the same reason. I'm sure there is a better way to do this, however I am not sure of it. Any help will be massively appreciated, thanks in advance.

In this case it would make more sense for the Scanner to use hasNextLine and then convert the String to an Integer. If that you could do something like this:

try {
   new Integer(inputScanner.hasNextLine);
} catch (Exception e) {
    System.out.println(“<error message>”)
}

In place of the if(inputScanner.hasNextInt()) due to the fact that the hasNextInt function will error out if there is not an Integer to be read.

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