麻烦我的While循环

时间:2017-07-04 08:42:40

标签: java loops while-loop

Java中的初学者,我创建了一个程序,该程序将在给出半径值后计算球体的面积和体积。如果半径<= 0,那么它应该以JOptionPane的形式显示错误消息,然后返回询问半径,但是,我正在努力使用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 个答案:

答案 0 :(得分:0)

此循环中的半径值永远不会改变

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

将其添加到循环

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

答案 1 :(得分:0)

另一种可能性(只是为了避免重复代码):

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