简体   繁体   English

Java,使用扫描仪时如何验证输入?

[英]Java, How do I validate input when using scanner?

I am currently working on Java code.我目前正在研究 Java 代码。 Basically, the int input works.基本上, int输入有效。 However, if I type in a character, the whole system crashes.但是,如果我输入一个字符,整个系统就会崩溃。 My question is as to what needs to be changed in the below code in order for the user to receive a message stating that only an int is the valid input, and to try again if they input a character.我的问题是在下面的代码中需要更改什么,以便用户收到一条消息,指出只有一个int是有效输入,并在他们输入字符时重试。

do {
    System.out.println("How many players would like to participate in this game?\t(2-4 players)");
    numberOfPlayers = in.nextInt();
} while(in.hasNextInt()); 

numberOfPlayers = in.nextInt();

I am currently working on Java code.我目前正在研究 Java 代码。 Basically, the int input works.基本上, int输入有效。 However, if I type in a character, the whole system crashes.但是,如果我输入一个字符,整个系统就会崩溃。 My question is as to what needs to be changed in the below code in order for the user to receive a message stating that only an int is the valid input, and to try again if they input a character.我的问题是需要在下面的代码中更改哪些内容,以便用户收到一条消息,指出只有int是有效输入,并在他们输入字符时重试。

do {
    System.out.println("How many players would like to participate in this game?\t(2-4 players)");
    numberOfPlayers = in.nextInt();
} while(in.hasNextInt()); 

numberOfPlayers = in.nextInt();

I personally prefer to use a while loop for this sort of thing rather than the do/while .我个人更喜欢对这种事情使用while循环而不是do/while Not that there is anything wrong with the do/while , I just feel it's more readable to use the while loop.并不是说do/while有什么问题,我只是觉得使用while循环更具可读性。

I agree with others here, accept String digits from the User instead of Integer. In my opinion it saves you other possible problems down the road and you have no need to purposely apply a try/catch mechanism should the User supply an invalid entry.我同意这里的其他人,接受来自用户的字符串数字而不是 Integer。在我看来,它可以为您节省其他可能的问题,并且如果用户提供无效条目,您无需特意应用try/catch机制。 It also allows you to easily apply a mechanism to quit the application which, again IMHO, should be made available to all Console app's.它还允许您轻松应用一种机制来退出应用程序,再次恕我直言,所有控制台应用程序都应该可以使用该机制。

You've got your answer for carrying out the task using a do/while loop but I would like to show you another way to do this sort of thing:您已经找到了使用do/while循环执行任务的答案,但我想向您展示另一种执行此类操作的方法:

Scanner in = new Scanner(System.in);
String ls = System.lineSeparator();
int numberOfPlayers = 0;
String userInput = "";

while (userInput.equals("")) {
    // The Prompt to User...
    System.out.print("How many players would like to participate in this game?" + ls 
            + "2 to 4 players only (q to quit): --> ");
    userInput = in.nextLine();

    // Did the User enter: q, quit (regardless of letter case) 
    if (userInput.toLowerCase().charAt(0) == 'q') {
        // No, the User didn't...
        System.out.println(ls + "Quiting Game - Bye Bye.");
        System.exit(0);  // Close (exit) the application.
    }

    /* Did the User supply a string representation of a numerical 
       digit consiting of either 2, 3, or 4.      */
    if (!userInput.matches("[234]")) { 
        // No, the User didn't...
        System.out.println("Invalid input! You must supply a number from 2 to 4 "
                         + "(inclusive)." + ls + "Try again..." + ls);
        userInput = "";
        continue;  // Loop again.
    }

    // Convert numerical string digit to an Ingeger value.
    numberOfPlayers = Integer.parseInt(userInput);
} 

System.out.println(ls + "The Number of players you provided is: --> " 
                 + numberOfPlayers);

You will notice that the Scanner#nextLine() method is used to accept User input as a String.您会注意到Scanner#nextLine()方法用于接受用户作为字符串的输入。 This now means that we need to validate the fact that a string representation of a Integer numerical digit (2 to 4 inclusive) was supplied by that User.现在这意味着我们需要验证该用户提供了 Integer 数字(包括 2 到 4)的字符串表示这一事实。 To do this you will notice that I used the String#matches() method along with a small Regular Expression (RegEx) which consists of the following string: "[234]" .为此,您会注意到我使用了String#matches()方法以及一个由以下字符串组成的小正则表达式(RegEx): "[234]" What this does in conjunction with the String#matches() method is it checks to see if the string value in the userInput variable contains either a single "2", a single "3", or a single "4".它与String#matches()方法一起执行的操作是检查userInput变量中的字符串值是否包含单个“2”、单个“3”或单个“4”。 Anything else other than any one of those three digits will display this message:除了这三个数字中的任何一个以外的任何其他数字都会显示此消息:

Invalid input! You must supply a number from 2 to 4 (inclusive).
Try again...

and, force the User make yet another entry.并且,强制用户再输入一次。

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

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