我的类得到错误的Java数组

时间:2011-10-06 21:34:05

标签: java arrays class object

我为我的对象创建了一个类:

    public class circles {

    int coor_x;
    int coor_y;

    int ray;


    public circles(int coor_x, int coor_y, int ray) {
    this.coor_x=coor_x;
    this.coor_y = coor_y;
    this.ray =ray ;

    }



  public int getCoor_x() {
        return coor_x;
    }

    public int getCoor_y() {
        return coor_y;
    }

      public int getRay() {
        return ray;
    }



    public void setCoor_x(int coor_x){
    this.coor_x=coor_x;
    }

     public void setCoor_y(int coor_y){
    this.coor_y=coor_y;
    }

      public void setRay(int ray){
    this.ray=ray;
    }


}

但是当我不想制作一个数组并用for填充它时,使用以下代码:

 int coor_x=2;
    int coor_y=2;
    int ray=2;
    int i = 0;    

    circles circles_test[]=new circles[10];


    for(i=0; i<=circles.length;){


        circles_test[i]=new circles(coor_x, coor_y, ray+i); //line 30
        System.out.println("Ray of circles: "+circles_test[i].getRay());
    i++;
    }

它有效,但有错误: 线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:10     在circlesObjectCreator.main(circlesObjectCreator.java:30) Java结果:1

我做错了什么?这是更好的原因吗?请帮忙,谢谢。

5 个答案:

答案 0 :(得分:5)

您正在访问一个包含10个元素的数组,索引为0-9,索引从0到数组长度为10,因为i <= circles.length。您想使用i < circles.length

答案 1 :(得分:2)

您的for循环检查circles.length的值,无论是什么,但您的数组都被称为circles_test。此外,您应该检查小于(< )比较,因为数组是从零开始的。 (长度不是数组中可用的最高索引,它是数组中元素的数量。)

答案 2 :(得分:2)

您的代码中存在多个错误。

首先,Circle类的更好名称是Circle。 Java类通常是大写的和单数的,而不是复数。

接下来,你的for循环太过分了。您的数组有10个元素,但Java中的数组是零索引的。这意味着circles_test中的第一个元素是circles_test[0],第二个元素是circles_test[1],依此类推。但是circles_test[10]不存在,因为那将是大小为10的数组中的第11个元素。这会导致ArrayIndexOutOfBoundsException,因为您尝试使用的索引10太大了。发生这种情况是因为你在for循环中写了这个:

i <= circles_test.length

这意味着i将一直包括circles_test.length。但是我们不希望它转到10,因为该索引超出范围,所以删除=符号。

接下来,编写for循环的更好方法是在循环中包含increment语句,如下所示:

for(i=0; i < circles.length; i++) {

}

for循环的工作方式如下:

for(first_statement; second_statement; third_statement)

first_statement将在循环开始时发生一次。每次在循环的一次重复开始时检查second_statement,如果为假,则循环结束。每次在循环结束时都会发生third_statement

如果您有任何疑问,可以随意提问。

答案 3 :(得分:1)

你制作了一个包含10个元素的数组,0-9。但是你的循环尝试访问0-10元素。

使用i<circles.length,这样就不会尝试访问不存在的元素10.

答案 4 :(得分:0)

Java数组的长度是独占的,这意味着:

length 0 =没有对象

length 1 =数组<0>中的一个对象

length 2 =两个对象,位置[0] [1]

因此,您需要将循环条件设为独占i<circles.length

另外,作为一个加号,for块可以初始化变量并递增它们:

for (int i = 0; i < circles.length; i++)