0

这是家庭作业。我添加了我认为是简单的 try-catch 语句,以确保用户输入双精度。一旦我这样做,我就会得到一个编译器错误,“半径无法解析为变量”我确信它很明显,但我没有得到它。我需要做什么来验证输入是否是有效的正数?

import javax.swing.*;

//Driver class
public class CylinderTest
{

    public static void main(String[] args)
    {
        boolean valid = false;

        Cylinder[] volume = new Cylinder[3];

                for (int counter = 0; counter < volume.length; counter++)
                {
                    //user input
                    try
                    {
                    double radius = Double.parseDouble(JOptionPane.showInputDialog("Enter the radius"));
                    }

                    catch (NumberFormatException e)
                    {
                        JOptionPane.showMessageDialog(null,
                                "Error. Please enter a valid number", "Error",
                                JOptionPane.INFORMATION_MESSAGE);
                    }
                    double height = Double.parseDouble(JOptionPane.showInputDialog("Enter the height"));
                    volume[counter] = new Cylinder(radius, height);
                }

        for (int i = 0; i < volume.length; i++)
        {
            System.out.println("for Radius of:" + volume[i].getRadius()
                    + " and Height of:" + volume[i].getHeight()
                    + " the Volume is:" + volume[i].volume());
        }
    }
}
4

2 回答 2

0

radius 变量的作用域在 try 块中结束。声明外面的半径。

 for (int counter = 0; counter < volume.length; counter++){
           //user input
     try{
          double radius = Double.parseDouble(JOptionPane.showInputDialog("Enter the radius"));
          double height = Double.parseDouble(JOptionPane.showInputDialog("Enter the height"));
          volume[counter] = new Cylinder(radius, height);
     }catch (NumberFormatException e)
                {
                    JOptionPane.showMessageDialog(null,
                            "Error. Please enter a valid number", "Error",
                            JOptionPane.INFORMATION_MESSAGE);
                }
            }
于 2013-09-28T17:43:44.507 回答
0

由于这是作业,我不会直接给你答案。您需要查看声明radius的位置以及该声明的位置如何影响代码其他块中变量的可见性。在哪里声明这些变量是至关重要的,你应该在课堂上完成一些工作。你很近,答案就在你面前。:)

于 2013-09-28T17:44:32.433 回答