该作业要求用户输入 3 个半径和 3 个高度条目,我将它们收集在一个数组中,然后确定每个条目的体积。我被困在阵列上。出于某种原因,我得到一个ArrayIndexOutOfBoundsException
.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
(CylinderTest.java:19)
我在最后(第 6 个,或第三个条目的高度)收到错误。我不明白我做错了什么。我很难理解逻辑,这是我最大的问题。
这是 CylinderTest (主要)
import javax.swing.*;
//Driver class
public class CylinderTest
{
public static void main(String[] args)
{
Cylinder[] volume = new Cylinder[3];
for (int counter = 0; counter < 6; counter++)
{
double radius = Double.parseDouble(JOptionPane
.showInputDialog("Enter the radius"));
double height = Double.parseDouble(JOptionPane
.showInputDialog("Enter the height"));
volume[counter++] = new Cylinder(radius, height);
}
String display = "Radius\tHeight\n";
for (Cylinder i : volume)
{
if (i != null)
display += i.toString() + "\n";
}
JOptionPane.showMessageDialog(null, display);
}
}
这是气缸类
public class Cylinder
{
// variables
public static final double PI = 3.14159;
private double radius, height, volume;
// constructor
public Cylinder(double radius, double height)
{
this.radius = radius;
this.height = height;
}
// default constructor
public Cylinder()
{this(0, 0);}
// accessors and mutators (getters and setters)
public double getRadius()
{return radius;}
public void setRadius(double radius)
{this.radius = radius;}
public double getHeight()
{return height;}
public void setHeight(double height)
{this.height = height;}
public double getVolume()
{return volume;}
public void setVolume(double volume)
{this.volume = volume;}
// Volume method to compute the volume of the cylinder
public double volume()
{return PI * radius * radius * height;}
public String toString()
{return volume + "\t" + radius + "\t" + height; }
}