我正在玩弄双数组,并试图将数组的所有偶数元素设置为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