这是家庭作业。我添加了我认为是简单的 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());
}
}
}