Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare scanners input with an array?

Tags:

java

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.

like image 541
John Avatar asked Nov 21 '25 22:11

John


1 Answers

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;
}
like image 98
Pokechu22 Avatar answered Nov 23 '25 11:11

Pokechu22



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!