2011-10-06 31 views
-2

我做了一個類爲我的對象:Java數組我的同班同學收到錯誤

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; 
    } 


} 

但當我不會做它的一個陣列,並用填充它,有了這個代碼:

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

我做錯了什麼?是更好的爲什麼呢?請幫忙,謝謝。

+1

嘗試'for(i = 0; i zengr

回答

5

你訪問具有10個元素的陣列,索引0-9,從0運行至陣列的長度,10的指數,這是因爲i <= circles.length的。你想使用i < circles.length

+0

感謝所有的快速回復..對我來說真是太遺憾了。 –

2

for循環檢查的circles.length的價值,不管它是什麼,但你的數組稱爲circles_test .Additionally你應該用小於(<)比較檢查,因爲數組是從零開始。 (長度不是陣列中可用的最高指數,它是在陣列中的元素數。)

1

你讓10個元素,0-9的陣列。但是你的循環試圖訪問元素0-10。

使用i<circles.length所以你不要試圖訪問不存在的元素10

0

的Java數組的lenght是排他性的,這意味着:

length 0 =無對象

length 1 =一個對象位於數組的位置[0]

length 2 =兩個對象,在位置[0] [1]

所以,你需要讓你的循環條件獨家i<circles.length

此外,作爲一個加時,for塊可以初始化變量,並增加他們:

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

2

有在你的代碼的幾個錯誤。

首先,圓圈類更好的名字是圈。 Java類通常是大寫和單數,而不是複數。

接下來,您的for循環走得太遠。你的數組有10個元素,但Java中的數組是零索引的。這意味着circles_test中的第一個元素是circles_test[0],第二個元素是circles_test[1],依此類推。但circles_test[10]不存在,因爲那將是你的尺寸10.這導致ArrayIndexOutOfBoundsException異常的數組中的第11要素,因爲你試圖使用索引10,這是太大了。這是發生,因爲你寫了這個在您的for循環:

i <= circles_test.length 

這意味着i將全力以赴直至幷包括circles_test.length的方式。但我們不希望它達到10,因爲該索引超出範圍,所以請刪除=標誌。

下,更好的方式來寫你的for循環,包括像這樣在循環增量聲明:

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

} 

For循環的工作是這樣的:

for(first_statement; second_statement; third_statement) 

first_statement會發生一次在循環的開始。 second_statement將在循環的一次重複開始時每次檢查一次,如果爲false,循環將結束。每次循環結束時都會發生third_statement

如果您有任何疑問,請隨時查詢。

+0

圈子的宣言純粹是文體。這可能會讓你不快,但肯定不是不正確的。 – Dave

+0

夠公平的,但我確實說「更好」。 – Jake

+0

不,你說「你錯誤地宣佈你的圓圈陣列。」 '圈子c [] =新圈子[10]'是完全有效的Java。 – Dave

相關問題