【发布时间】:2016-02-25 16:05:05
【问题描述】:
我需要允许用户在程序中输入他们想要的内容,但仅限于 R、T 和 Q 这三个选项。我尝试过多次这样做,但最终还是重复了几次。我想出了这个解决方案,但是现在当我运行代码时,无论我在控制台中输入什么,它都会简单地循环。任何帮助将不胜感激,谢谢。
公共类绘制{
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()));
}
【问题讨论】:
-
您检查的是
options.equals,而不是choice.equals。另外,循环上的保护条件是什么意思?options中没有小写字母 - 为什么不直接使用while (true)?