如何将扫描仪输入与数组进行比较?

时间:2014-09-03 23:35:49

标签: java

我想知道如何比较扫描仪和数组的输入。很抱歉,如果这是一个简单的问题,但我对Java很新。

这是我写的:

    public static void handleProjectSelection() {

    Scanner getProjectNum = new Scanner(System.in);
    int answer;
    int[] acceptedInput = {1, 2, 3};//The only integers that are allowed to be entered by the user.


    System.out.println("Hello! Welcome to the program! Please choose which project" +
    "you wish to execute\nusing keys 1, 2, or 3.");
    answer = getProjectNum.nextInt(); //get input from user, and save to integer, answer.
        if(answer != acceptedInput[]) {
            System.out.println("Sorry, that project doesn't exist! Please try again!");
            handleProjectSelection();//null selection, send him back, to try again.
        }

}

我希望用户只能输入1,2或3.

任何帮助将不胜感激。

谢谢。

2 个答案:

答案 0 :(得分:3)

您可以使用此功能:

public static boolean isValidInput(int input, int[] acceptedInput) {
    for (int val : acceptedInput) { //Iterate through the accepted inputs
        if (input == val) {
            return true;
        }
    }
    return false;
}

请注意,如果您正在使用字符串,则应使用此字符串:

public static boolean isValidInput(String input, String[] acceptedInput) {
    for (String val : acceptedInput) { //Iterate through the accepted inputs
        if (val.equals(input)) {
            return true;
        }
    }
    return false;
}

答案 1 :(得分:0)

您可以使用Arrays类中的二进制搜索,它将为您提供给定整数的索引位置。

<强>样品:

 if(Arrays.binarySearch(acceptedInput , answer ) < 0)  {
        System.out.println("Sorry, that project doesn't exist! Please try again!");
        handleProjectSelection();//null selection, send him back, to try again.
 }

如果结果为否定,则answer不会位于您的数组中