[英]Break a while loop without using If or 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;
}
}
有什么幫助嗎?
您可以拋出一個您捕獲並忽略的異常。 這是個壞主意,因為
但是,由於您使用的是 while 循環,就像使用 if & break 一樣,您可以執行以下操作。
NotNegative = h >= 0;
讀取輸入后,在while(NotNegative){
添加以下代碼。
NotNegative = h >= 0;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.