如何在`do while`循环中命令返回顶部?

时间:2014-10-16 19:54:52

标签: java while-loop

我对这个do while声明感到困惑。我希望如果用户输入y,那么它将循环回do循环。我不确定如何命令回do循环,C++如果我没有弄错,可以使用goto关键字。

do
    {
    System.out.print( "\nPlease Make A Choice :");
    input = stdin.readLine();
    x = Integer.parseInt(input);

    if (x == 1)     
        CalculateCircleArea.GetRadius();    
    else if (x == 2)
        CalculateRectangleArea.GetLengthAndHeight();
    else if (x == 3) 
        CalculateTriangleArea.GetHeightBaseAndBaseLength();
    else

    System.out.print("\t      WRONG INPUT");
    String input2;
    String abc = "\n\tDO YOU WANT TO CONTINUE?";
    String abc2 = "\n\t   PLEASE CHOOSE (Y/N):";
    String abc3 = abc.concat(abc2);
    System.out.print(abc3);
    input2 = stdin.readLine();  
    }while (choice == 'y');

5 个答案:

答案 0 :(得分:3)

您可以使用 continue 语句开始循环的新迭代。

do{
    ...
    continue;    // Stops the current loop and continues to the next iteration.
    ...
}while(...);

另外,我可以对代码进行一些改进。

使用此

x = stdin.nextInt();

而不是

input = stdin.nextLine();
x = Integer.parseInt(input);

Scanner.nextInt()将返回它找到的下一个整数,并且比读取字符串并将其转换为int更有效。但是,在使用try-catch块检查输入错误时,使用当前配置很有用。

使用

System.out.print("\n\tDO YOU WANT TO CONTINUE? \n\t    PLEASE CHOOSE (Y/N)");

而不是

String abc = "\n\tDO YOU WANT TO CONTINUE?";
String abc2 = "\n\t   PLEASE CHOOSE (Y/N):";
String abc3 = abc.concat(abc2);
System.out.print(abc3);

前者只是有意义且效率更高,因为你不必连接字符串等。

此外,choice似乎无法在任何地方声明或使用。你确定你不应该使用input2吗?如果是,请使用String.equalsIgnoreCase("")方法而不是==,因为==会比较对象引用而不是值。

答案 1 :(得分:2)

应该使用:

while(choice.equalsIgnoreCase("y"))

而不是==这不用于比较字符串。

另外,我没有看到选择设置你可能需要输入2而不是选择?

while(input2.equalsIgnoreCase("y")

答案 2 :(得分:1)

我认为您应该将用户输入读入正确的变量:

//...
  input2 = stdin.readLine();  
}while (choice == 'y');

替换为

//...
  choice = stdin.readLine();  
}while ("y".equals(choice));

答案 3 :(得分:0)

条件不应该是这样的吗?

    input2 = stdin.readLine();  
}
while (input2.equals("y"));

答案 4 :(得分:0)

choice用作String只是为了简化您的解决方案。

do{
    //.. 
    }while (choice == "y");

如果choiceinterned,此代码将是正确的,否则使用equals()方法来比较字符串是好的。

do{
    //...
    input2 = stdin.readLine();  
}
while (input2.equals("y"));

了解更多details