在 Java 中检查用户输入是否仅为整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15960434/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 21:27:11  来源:igfitidea点击:

Checking for user input to be only integers in Java

javatry-catchuser-input

提问by user2272351

I'm doing lottery game for my assignment (user inputs 6 number, i will generate 8 unique winning numbers and 2 last numbers are supplementary). I need help with user input checking if input numbers are from 1 to 45 and input must be int, when input is not integer it throws an error.

我正在为我的任务做彩票游戏(用户输入 6 个号码,我将生成 8 个唯一的中奖号码,最后 2 个号码是补充号码)。我需要帮助用户输入检查输入数字是否从 1 到 45 并且输入必须是 int,当输入不是整数时,它会引发错误。

This programming way is procedure way, how can i change it into object oriented way? I know that I must make methods in another java file and then link it back to this main. Can you suggest me how to do it?

这种编程方式是过程方式,我如何才能将其更改为面向对象的方式?我知道我必须在另一个 java 文件中创建方法,然后将它链接回这个 main.js 文件。你能建议我怎么做吗?

I have tried try and catch, if and else (for input check) but i don't know how to check user input when it's in array. Thank you for help.

我尝试过 try 和 catch、if 和 else(用于输入检查),但我不知道如何在数组中检查用户输入。谢谢你的帮助。

Here is my code:

这是我的代码:

class Lottery {

public static void main ( String[] args ) {

    System.out.println("\nWelcome to the Lottery game.");
    System.out.println("You can enter numbers from 1 to 45.");

    // User input into an array
    int[] input = new int[6];

    Scanner scanner = new Scanner(System.in);

    System.out.println("\nPlease enter your 6 lucky numbers: ");
    for(int j = 0; j < 6; j++) {

        input[j]=scanner.nextInt();
    }

    int check = scanner.nextInt();
    if(check < 0 && check > 45) {
        System.out.println("\nERROR: Please enter only numbers from 1 to 45!");
    }

    // Printing out unique winning numbers from random generator
    System.out.println("\nWinning numbers: ");
    MultiRandomGenerator mrg = new MultiRandomGenerator();
    int[] set;

    set = mrg.getSet();
    for (int i = 0; i < set.length; i++) {

        System.out.print(set[i] + " ");
    }

    // Loops for counting how many numbers user has guessed right
    int count = 0; // for 6 numbers
    int scount = 0; // for 2 last supplementary numbers

    for(int i = 0; i < input.length; i++) {

        for(int k = 0; k < set.length; k++) {

            if (k < 6) {

                if (set[k] == input[i]) {

                    count++;
                } else {
                    if (set[k] == input[i]) {

                    scount++;
                    }

                }

            }

        }
    }
    System.out.print("\n\nYou guessed right " + count + " winning numbers.");
    System.out.print("\nYou guessed right " + scount + " suplementary numbers.");

    // If statments for printing out winning prizes
    if (count == 6) {

        System.out.println("\nYou have won 1st price!");
    } if (count == 5 && scount == 1) {

        System.out.println("\nYou have won 2st price!");
    } if (count == 5) {

        System.out.println("\nYou have won 3st price!");
    } if (count == 4) {

        System.out.println("\nYou have won 4st price!");
    } if (count == 3 && scount == 1) {

        System.out.println("\nYou have won 5st price!");
    } if (count == 1 && scount == 2) {

        System.out.println("\nYou have won 6st price!");
    } else {

        System.out.println("\nSorry, you didn't won anything.");
    }
}
}

回答by Joseph Selvaraj

Sample code to go through array and find the invalid user input.

遍历数组并查找无效用户输入的示例代码。

set = mrg.getSet();
String[] userDataStatus = new String[45];
for (int i = 0; i < set.length; i++) 
{
    try
    {
        String inputdata = set.get(i);
        if(inputdata != null && inputdata.trim().length() > 0)
        {
            int currentNumber = Integer.parseInt(userdata);
            userDataStatus[i] = "Y";//Y represent valid number
        }
    }
    catch (NumberFormatException ex )
    {
        userDataStatus[i] = "N";//If it throws exception then save as 'N'       
    }
}

Use the above String array and display error messaage to users.

使用上面的字符串数组并向用户显示错误消息。

回答by Orn Kristjansson

You can check in your loop, something like

你可以检查你的循环,比如

int val;
try
{
   input[j] = Integer.parseInt( scanner.nextString() );
}
catch (NumberFormatException ex )
{

}