How do I compare the input from scanners to an array?

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

Here's what I wrote:

    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 be able to only enter 1, 2 or 3.

Any help would be greatly appreciated.

Thank.

+3


source to share


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

      



Please note, 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;
}

      

+3


source


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

Example:



 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, answer

it is not in your array

0


source







All Articles