1

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

有什么帮助吗?

4

2 回答 2

2

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

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

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

NotNegative = h >= 0;
于 2012-12-03T17:01:52.207 回答
0

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

NotNegative = h >= 0;
于 2012-12-03T17:10:38.660 回答