java - 不使用 If 或 Break 中断 while 循环

标签 java if-statement while-loop break

我需要创建一个程序,使用 while 来查找圆柱体的体积。如果用户输入高度的负值,我需要 while 循环中断。我的代码如下所示:

double sentinel=1, h=1, v=0, r, count=0; // declares all variables needed
    final double PI=3.14159;
    boolean NotNegative=true;

while(NotNegative){// && count==0){ // while both the height is positive AND the total times run is 0
        System.out.print("Enter height (Use negative to exit): "); // has the user input the height
        h=Double.parseDouble(br.readLine());
        sentinel=h; // save sentinel as the inputted height

        while(sentinel>0){

           System.out.print("Enter radius: "); // have the user input the radius
           r=Double.parseDouble(br.readLine());
           v=PI*(r*r)*h; // find the volume
           System.out.println("The volume is " + v); // print out the volume
           count++; // increase the count each time this runs
           NotNegative=true;
           sentinel=-1;
        }
    }   

有什么帮助吗?

最佳答案

您可以抛出一个异常,您可以捕获并忽略该异常。这是个坏主意,因为

  • if 和/或 break 更高效、更简单。
  • 很慢
  • 这很令人困惑。

但是,由于您使用的是 while 循环,这类似于使用 if & break,因此您可以执行以下操作。

NotNegative = h >= 0;

关于java - 不使用 If 或 Break 中断 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13688085/

相关文章:

适合初学者的 Java 线程

java - 通过给定颜色 Int 的因子获得更深的颜色

java - 帮助打破 if/else 吗?

java - While 循环不适用于 Try/Catch 语句

java - 使用 jxl(java) 为 HYPERLINK 编写 excel 公式失败

java - Maven 插件配置将参数设置为类

jQuery if 语句将 div 类更改为另一个 not 类

c# - 如果大于 C#

python - 在循环选择题时?

c++ - 使用循环 C++ 输入成绩