这是作业。我添加了我认为是一个简单的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());
}
}
}
您需要在更大范围内声明'radius'。 –
@SotiriosDelimanolis:实际上,我认为将'radius'和'height'的引用放在'try'块中会更有意义。 –
是的,我也想过移动半径引用来尝试块,并为其他异常添加一个catch块 – upog