2

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

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

4

2 回答 2

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

对于更多的选项,您可以使用 aSet来存储所有接受的选项。

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));
于 2020-07-05T01:12:23.397 回答
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 中按照约定以小写字母开头。

(不得不编辑它,因为我对咖啡一无所知。)

于 2020-07-05T00:59:02.630 回答