【问题标题】:Break a while loop without using If or Break在不使用 If 或 Break 的情况下中断 while 循环
【发布时间】:2012-11-21 04:54:01
【问题描述】:

我需要创建一个使用 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;
        }
    }   

有什么帮助吗?

【问题讨论】:

  • 那你为什么不想要 break 或者 if 呢?
  • Math.PI 是不是太准确了? ;)

标签: java if-statement while-loop break


【解决方案1】:

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

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

但是,由于您使用的是 while 循环,就像使用 if & break,您可以执行以下操作。

NotNegative = h >= 0;

【讨论】:

    【解决方案2】:

    在读取输入后,在while(NotNegative){ 中添加以下代码。

    NotNegative = h >= 0;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-14
      • 1970-01-01
      • 2019-04-26
      • 1970-01-01
      相关资源
      最近更新 更多