Java 在不使用If或Break的情况下中断while循环
我需要创建一个程序,使用while来查找圆柱体的体积。如果用户为高度输入负值,我需要中断while循环。我的代码如下所示:Java 在不使用If或Break的情况下中断while循环,java,if-statement,while-loop,break,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 b
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更高效、更简单
- 很慢
- 这令人困惑
NotNegative = h >= 0;
读取输入后,在
while(NotNegative){
中添加以下代码
NotNegative = h >= 0;
你为什么不想休息一下呢,或者如果呢?
Math.PI
太精确了吗?;)