2013-09-28 29 views
0

这是作业。我添加了我认为是一个简单的try-catch语句,以确保用户输入一个double。只要我这样做,我会得到一个编译器错误,“半径不能解析为变量”我肯定它的东西很明显,但我没有得到它。我需要做什么来验证输入是有效的正数?Java试试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

您需要在更大范围内声明'radius'。 –

+1

@SotiriosDelimanolis:实际上,我认为将'radius'和'height'的引用放在'try'块中会更有意义。 –

+0

是的,我也想过移动半径引用来尝试块,并为其他异常添加一个catch块 – upog

回答

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

@FredLarson:是的,我包括你在之前的评论中建议的另一种方式。谢谢.. – NewUser

+0

我没有理由在第二个例子中的'try'块之外声明'radius'。另外,这个'volume [counter] =新的Cylinder(半径,高度);'不需要重复行。 – Elist

0

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

+0

谢谢。我知道这是显而易见的,但我看不到它。再次感谢 – user2802785