我需要创建一个程序,使用 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/