简体   繁体   English

isDigit验证

[英]isDigit validation

I'm trying to validate for an input of either 1 or 2. But, with this code, if you enter letters, it crashes the program. 我正在尝试验证输入1或2。但是,使用此代码,如果您输入字母,则会使程序崩溃。

How can this be fixed? 如何解决?

System.out.print("Choice: ");
userSelection  = keyboard.nextInt();

while (flag == 0)
{
    if (userSelection == 1 || userSelection == 2)
    {
        flag = 1;
    }
    if(Character.isDigit(userSelection))
    {
        flag = 1;
    }
    else 
    {
        flag = 0;
    }
    if (flag == 0)
    {
        //this is a system clear screen to clear the console
        System.out.print("\033[H\033[2J");  
        System.out.flush(); 

        //display a warning messege that the input was invalid
        System.out.println("Invalid Input! Try again, and please type in selection 1 or selection 2 then hit enter");
        System.out.print("Choice: ");
        userSelection  = keyboard.nextInt();
    }
}

nextInt expects the user to type an integer. nextInt希望用户键入一个整数。 It will fail otherwise. 否则将失败。

You may want to construct something with nextLine (which reads a line of input that you can then inspect, reading single characters as they are being typed is tricky in Java ). 您可能想用nextLine构造一些东西(它读取一行输入,然后您可以检查这些输入, 在键入单个字符时读取它们在Java中是棘手的 )。

Try this code snippet: 尝试以下代码片段:

try (Scanner scanner = new Scanner(System.in)) {
   int choice;
   while (true) {
       System.out.print("Choice: ");
       if (!scanner.hasNextInt()) {
            scanner.nextLine();//read new line character
            System.err.println("Not a number !");
            continue; // read again
       }
       choice = scanner.nextInt(); //got numeric value
       if (1 != choice && 2 != choice) {
             System.err.println("Invalid choice! Type 1 or 2 and press ENTER key.");
             continue; //read again
       }
       break;//got desired value
   }
   System.out.printf("User Choice: %d%n", choice);
}

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

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