Is there a way to limit the user inputs to two or three options

Viewed 99

In the userInput function in Java has the person type in anything, is there anyway I could limit that to 2 options. Here is my code

import java.util.Scanner;

public class Intelijence {
    public static void main(String[] args) throws InterruptedException {
        Scanner playerInput;
        playerInput = new Scanner(System.in);
        String Question1;

        System.out.println("Ugh, I need some coffee");
        Thread.sleep(1000);
        System.out.println("'What kind of coffee should he drink'");
        Question1 = playerInput.nextLine();
        System.out.println(Question1);
    }
}

So how can I set the option to something like light or dark roast?

2 Answers
List<String> acceptableAnswers = List.of("Light", "Dark", "Iced");
if (!acceptableAnswers.contains(Question1)) {
    System.out.println("You don't know anything about coffee, do you?");
}

You should then probably ask for a new input, which I leave as an exercise to the reader.

BTW, "Question1" is a bad name for a variable for two reasons: 1) it contains an answer, not a question, and 2) variable names start with a lowercase letter in Java by convention.

(Had to edit that because I am clueless about coffee.)

You can use a do...while loop to loop until the user enters a valid input.

do {
    System.out.println("'What kind of coffee should he drink'");
    Question1 = playerInput.nextLine();
} while(!Question1.equals("light roast") && !Question1.equals("dark roast"));

For a larger amount of options, you can use a Set to store all the accepted ones.

final Set<String> accepted = Set.of("light roast", "dark roast");
do {
    System.out.println("'What kind of coffee should he drink'");
    Question1 = playerInput.nextLine();
} while(!accepted.contains(Question1));
Related