【发布时间】:2013-10-04 07:50:14
【问题描述】:
该任务要求用户输入 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);
}
}
这里是 Cylinder 类
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; }
}
【问题讨论】:
-
Firstable,如果你这样做:
volume[counter++]然后你将移动计数器两次,一次在 volume[counter++] 中,另一次在 for 语句中; counter++) -
为了将来的调试参考,
CylinderTest.java:19将您指向发生错误的类 (CylinderTest.java) 和该类中的行号 (19)。 #19 到底是哪一行? -
这是一个很好的家庭作业问题尝试。我认为正是 nhgrif 所建议的缺失了。在这种情况下,CylinderTest 类是无关紧要的,因为问题与数组有关。我认为它不值得投反对票。
-
第 19 行是体积[counter++] = new Cylinder(radius, height);
-
另外,据我所知,在 update 语句之外的任何地方混用
for loop的迭代器是非常糟糕的做法。
标签: java arrays indexoutofboundsexception