Java Try Catch错误

时间:2013-09-28 17:40:52

标签: java try-catch

这是作业。我添加了我认为是一个简单的try-catch语句,以确保用户输入double。一旦我这样做,我得到一个编译器错误,“半径无法解析为变量”我确定它显而易见,但我没有得到它。我需要做些什么才能验证输入是有效的正数?

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());
        }
    }
}

2 个答案:

答案 0 :(得分: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);
                }
            }

答案 1 :(得分:0)

由于这是作业,我不会直接给你答案。您需要查看声明radius的位置以及该声明的位置如何影响代码其他块中变量的可见性。你声明这些变量的地方很重要,你应该把它作为课程的一部分。你很亲密,答案就在你面前。 :)