2017-07-04 90 views
-2

Java中的初學者在這裏,我正在創建一個程序,該程序將在給出半徑值後計算球體的面積和體積。如果半徑爲< = 0,那麼它應該以JOptionPane的形式顯示錯誤消息,然後返回以詢問半徑,但是,我正在用while循環掙扎。我的while循環出現問題

這裏是我的代碼:

public static void main(String[] args) { 
    String volume = "V = (4(pi)r^3)/3"; 
    String area = "V = 4(pi)r^2"; 
    JOptionPane.showMessageDialog(null, "Formulas for a Sphere:"+"\n"+"V = (4(pi)r^3)/3"+"\n"+"A = 4(pi)r^2"); 
    Double radius = Double.parseDouble(JOptionPane.showInputDialog("Enter Radius(cm)")); 
    while(radius <= 0) { 
     JOptionPane.showMessageDialog(null, "Please insert a valid radius."); 
    } 
    JOptionPane.showMessageDialog(null, volume + " = " + Math.round((4*3.1415*Math.pow(radius,3)/3)) + "cm" + 
      "\n" + area + " = " + Math.round(4*3.1415*Math.pow(radius,2))); 
+2

您需要輸入_inside_您的循環。否則,循環將如何結束? – khelwood

回答

0

半徑值永遠不會改變在這個循環中

while(radius <= 0) { 
    JOptionPane.showMessageDialog(null, "Please insert a valid radius."); 
} 

加入到循環這個

radius = Double.parseDouble(JOptionPane.showInputDialog("Enter Radius(cm)")); 
+0

啊哈!我試圖做類似的事情,但不小心試圖重新啓動變量。非常感謝你 –

0

另一種可能(只是爲了避免複製代碼):

while (true) { 
    Double radius = Double.parseDouble(JOptionPane.showInputDialog("Enter Radius(cm)")); 
    if (radius > 0) 
     break; 
    JOptionPane.showMessageDialog(null, "Please insert a valid radius."); 
}