我有一個大小爲50的整數數組。 所以,如你所知,最初這個數組的元素值將全爲0。 我需要做的是: 如果數組= [12,10,0,0,...... 0],for循環只需要考慮非零元素,所以循環應該被執行同樣,如果數組爲= [0,0,0,...... 0],則for循環不應該執行,因爲所有元素均爲零。 如果數組是[12,10,5,0,17,8,0,0,.......,0],則for循環應該爲前6個元素執行,即使其中一個內部元素爲零。Integer數組訪問 - Java
這是我的。這給了我一個IndexOutOfBoundsException.Please幫助。 此外,有沒有什麼辦法可以動態增加int數組的大小,而不是將大小設置爲50,然後在循環中使用它? thx在advacance任何幫助!
int[] myArray = new int[50];
int cntr = 0;
int x = getXvalue();
int y = getYvalue();
if (x>y){
myArray[cntr] = x;
cntr++;
}
for (int p=0; p<= myArray.length && myArray[p]!=0 ; p++){
//execute other methods..
}
// SOLUTION:
我利用一個ArrayList代替的int數組動態增加陣列的尺寸。
ArrayList<Integer> myArray = new ArrayList<Integer>();
To set the value of the elements-
myArray.add(cntr, x); // add(index location, value)
考慮使用'ArrayList'。它使用簡單,可以動態調整大小。 – Dawood 2012-01-30 06:33:09
哪一行引發異常? – Arjan 2012-01-30 06:37:14
@Arjan - for循環拋出一個異常 – user656523 2012-01-30 06:40:44