简体   繁体   English

如何在 Java 中验证用户输入

[英]How can I validate user input in Java

I am currently experimenting with Java, trying to get the user to input an integer.我目前正在试验 Java,试图让用户输入一个整数。 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").目前上面的代码给出了一个异常错误(“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.我曾尝试使用 try/catch 但这并没有真正起作用,因为我希望用户每次不输入整数时都能看到第二条消息(“您需要输入一个整数”)而我不想出于同样的原因,它会围绕主运行循环重新循环。 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.在这种情况下,扫描器使用hasNextLine然后将字符串转换为整数会更有意义。 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.代替if(inputScanner.hasNextInt())因为如果没有要读取的整数,hasNextInt 函数将出错。

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

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