有没有一种方法可以将用户输入限制为两个或三个选项

时间:2020-07-05 00:51:39

标签: java user-input

在Java的userInput函数中,任何类型都有人员类型,无论如何我可以将其限制为2个选项。这是我的代码

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

那么如何将选项设置为浅或深烤?

2 个答案:

答案 0 :(得分:2)

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

然后您可能应该请求一个新输入,我将其作为练习留给读者。

顺便说一句,“ Question1”是变量的坏名,有两个原因:1)它包含答案,而不是问题; 2)按照惯例,变量名在Java中以小写字母开头。

(由于我对咖啡一无所知,因此不得不进行编辑。)

答案 1 :(得分:2)

您可以使用do...while循环进行循环,直到用户输入有效的输入为止。

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

对于大量选项,您可以使用Set存储所有接受的选项。

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