我正在玩弄雙數組,並試圖將數組的所有偶數元素設置爲0,並將數組中的所有奇數元素都設置爲1。 ,但是當我運行它時,我收到了一堆錯誤。不知道有什麼問題;我一直在尋找它一段時間沒有運氣。如何解決它提供的錯誤的任何建議將是非常好的,謝謝!甚至設置爲0,奇數設置爲1
代碼:給定
public class SetOf0and1 {
public static void main(String[]args)
{
int [][] numbers1 = {{4,2,5}, {2,4,1}, {1,3}};
System.out.println("Before setting elements between 0 and 1: ");
displayArray(numbers1);
setEvenRowsTo0OddRowsTo1 (numbers1);
System.out.println("After setting the elements between 0 and 1");
displayArray(numbers1);
}
public static void setEvenRowsTo0OddRowsTo1(int [][]array)
{
for(int i=0; i<array.length;i++)
{
for(int j=0; j<array[i].length;j++)
{
if(i%2 == 0)
array[i][j]=0;
else
array[i][j]=1;
}
}
}
public static void displayArray(int [][]array)
{
for(int i=0;i<array.length;i++)
{
for(int j=0; j<array.length;j++)
{
System.out.println(array[i][j] + " ");
}
System.out.println();
}
}
}
錯誤:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at SetOf0and1.displayArray(SetOf0and1.java:38)
at SetOf0and1.main(SetOf0and1.java:10)
注意:如果'(ⅰ%2 == 0)陣列[i] [j] = 0; else array [i] [j] = 1;'可以寫得更簡單:'array [i] [j] = i%2;'' – assylias 2014-09-13 19:12:07