【问题标题】:Do - While loop does not move on after user inputs correct or incorrect parametersDo - 用户输入正确或不正确的参数后,While 循环不会继续
【发布时间】: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)

标签: java arrays loops


【解决方案1】:

尝试使用choice 而不是options 来编写if 条件,如下所示:

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

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

while(!list.contains(choice));  

【讨论】:

  • 支持while 的想法:)
【解决方案2】:

您的条件正在检查错误的变量:

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

应该是

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

【讨论】:

  • 谢谢安迪!这样一个小而愚蠢的错误。非常感谢所有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-06
  • 1970-01-01
相关资源
最近更新 更多