首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java,如何在使用scanner时验证输入?

Java,如何在使用scanner时验证输入?
EN

Stack Overflow用户
提问于 2020-03-10 05:55:50
回答 1查看 632关注 0票数 0

我目前正在编写Java代码。基本上,int输入是有效的。但是,如果我输入一个字符,整个系统就会崩溃。我的问题是,为了让用户接收到一条消息,声明只有一个int是有效输入,并在输入字符时重试,需要在下面的代码中进行哪些更改。

代码语言:javascript
复制
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();
EN

回答 1

Stack Overflow用户

发布于 2020-03-10 08:06:28

我个人更喜欢使用while循环来处理这类事情,而不是使用do/while。并不是说do/while有什么问题,我只是觉得使用while循环更具可读性。

我同意其他人的观点,接受来自用户的字符串数字,而不是整数。在我看来,它省去了您以后可能遇到的其他问题,而且如果用户提供了无效的条目,您也不需要特意应用try/catch机制。它还允许你很容易地应用一种机制来退出的应用程序,再一次,我的,应该使所有的控制台应用程序的。

您已经得到了使用 do /while循环执行任务的答案,但我想向您展示完成此类任务的另一种方法:

代码语言:javascript
复制
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);

您会注意到,Scanner#nextLine()方法用于将用户输入作为字符串接受。这意味着我们现在需要验证以下事实:该用户提供了整数数字(2到4)的字符串表示。为此,您会注意到,我使用了String#matches()方法和一个小的Regular Expression (RegEx),它由以下字符串组成:"[234]"。它与String#matches()方法一起执行的是检查userInput变量中的字符串值是否包含单个"2“、单个"3”或单个"4“。这三个数字中的任何一个以外的任何其他数字都将显示此消息:

代码语言:javascript
复制
Invalid input! You must supply a number from 2 to 4 (inclusive).
Try again...

并且,强制用户输入另一个条目。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60608877

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档