3

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.

2
  • Think about it in reverse. Does the group of elements 1,2,3 contain your input? Commented Sep 3, 2014 at 23:36
  • compare it to acceptedInput[i] for each index of the array. Commented Sep 3, 2014 at 23:37

2 Answers 2

3

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

Note that this requires the array to be sorted.
@immibis he only have 3 items no need to sort it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.