Do - 在用户输入正确或不正确的参数后,While循环不会继续

时间:2016-02-25 16:05:05

标签: java arrays loops

我需要允许用户将他们想要的内容输入到程序中,但仅限于R,T和Q三个选项。我曾尝试多次这样做,最后又多次回到自己身上。我想出了这个解决方案,但现在当我运行代码时,无论我进入控制台,它都会循环。非常感谢任何帮助,谢谢。

公共类Draw {

public static void main(String [] args){

String[] options = {"R","T","Q"};
String choice;
List<String> list = Arrays.asList(options);
    Scanner scanner = new Scanner (System.in);
do {
        System.out.println("Press 'R' to start drawing a Rectangle.");
        System.out.println("Press 'T' to start drawing a Triangle.");
        System.out.println("Press 'Q' to stop.");

        System.out.print("Enter one of the options: "); 
        choice = scanner.next();
        if (options.equals("R")) {
            System.out.println("You have selected to draw a Rectangle!");
            System.out.println("Please enter the Height and Width of the rectangle that is within 30cm - 90cm: ");

        }
        else if (options.equals("T")) {
            System.out.println("You have selected to draw a Tringle! Enter the three angles of the triangle between 30cm and 90cm: ");

        }
            else if (options.equals("Q")) {
                System.out.println("Thank you for drawing with the finch, good bye.");
            }
            else {
                System.out.println("Invalid input, try again. Enter with a capital letter one of the three options.");
            }
}
while(!list.contains(choice.toLowerCase()));

}

2 个答案:

答案 0 :(得分:3)

尝试使用if代替choice来编写options条件,如下所示:

 if ("R".equals(choice)) {
 ...
 else if ("T".equals(choice)) {
 ...
 else if ("Q".equals(choice)) {

从while循环中删除方法toLowerCase是不必要的:

while(!list.contains(choice));  

答案 1 :(得分:2)

您的条件是检查错误的变量:

choice = scanner.next(); 
if (options.equals("R")) {

应该是

choice = scanner.next(); 
if (choice.equals("R")) {