简体   繁体   中英

How to compare scanners input with an array?

I was wondering how I can compare the input from a scanner, to an array. Sorry if this is an easy question, but I'm fairly new to Java.

Here's what I've written:

    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.
        }

}

I want the user to only be able to input 1, 2, or 3.

Any help would be appreciated.

Thank you.

You can use this function:

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

Note that if you are working with strings, you should use this instead:

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;
}

You can use the binary search from Arrays class which will give you the index location of the given integer.

sample:

 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.
 }

If the result is negative then the answer does not located in your array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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