如何修复ArrayIndexOutOfBoundException:4

时间:2015-02-28 21:03:17

标签: arrays indexoutofboundsexception

我正在尝试创建一个二维数组并使用此代码

public void createPwm()
{
   double[ ][ ] aryNumbers = new double[4][8];
   aryNumbers[0][0] = new Double((3 + .1) / (10 + 4 * 0.1));
   aryNumbers[0][1] = new Double((2 + .1) / (10 + 4 * 0.1));
   aryNumbers[0][2] = new Double((1 + .1) / (10 + 4 * 0.1));
   aryNumbers[0][3] = new Double((4 + .1) / (10 + 4 * 0.1));
   aryNumbers[1][0] = new Double((4 + .1) / (10 + 4 * 0.1));
   aryNumbers[1][1] = new Double((3 + .1) / (10 + 4 * 0.1));
   aryNumbers[1][2] =  new Double((2 + .1) / (10 + 4 * 0.1));
   aryNumbers[1][3] =  new Double((1 + .1) / (10 + 4 * 0.1));
   aryNumbers[2][0] = new Double((1 + .1) / (10 + 4 * 10));
   aryNumbers[2][1] = new Double((1 + .1) / (10 + 4 * 10));
   aryNumbers[2][2] = new Double((6 + .1) / (10 + 4 * 10));
   aryNumbers[2][3] =  new Double((2 + .1) / (10 + 4 * 10));
   aryNumbers[3][0] = new Double((0 + .1) / (10 + 4 * 10));
   aryNumbers[3][1] = new Double((0 + .1) / (10 + 4 * 10));
   aryNumbers[3][2] = new Double((10 + .1) / (10 + 4 * 10));
   aryNumbers[3][3] = new Double((0 + .1) / (10 + 4 * 10));
   aryNumbers[4][0] =  new Double(.1 / (10 + 4 * 10));
   aryNumbers[4][1] = new Double((10 + .1) / (10 + 4 * 10));
   aryNumbers[4][2] = new Double((0 + .1) / (10 + 4 * 10));
   aryNumbers[4][3] = new Double((0 + .1) / (10 + 4 * 10));
   aryNumbers[5][0] = new Double((6 + .1) / (10 + 4 * 10));
   aryNumbers[5][1] = new Double((0 + .1) / (10 + 4 * 10));
   aryNumbers[5][2] = new Double((4 + .1) / (10 + 4 * 10));
   aryNumbers[5][3] =  new Double((0 + .1) / (10 + 4 * 10));
   aryNumbers[6][0] = new Double((8 + .1) / (10 + 4 * 10));
   aryNumbers[6][1] = new Double((0 + .1) / (10 + 4 * 10));
   aryNumbers[6][2] = new Double((2 + .1) / (10 + 4 * 10));
   aryNumbers[6][3] =  new Double((0 + .1) / (10 + 4 * 10));
   aryNumbers[7][0] = new Double((0 + .1) / (10 + 4 * 10));
   aryNumbers[7][1] = new Double((0 + .1) / (10 + 4 * 10));
   aryNumbers[7][2] = new Double((9 + .1) / (10 + 4 * 10));
   aryNumbers[7][3] = new Double((1 + .1) / (10 + 4 * 10));
   aryNumbers[8][0] =  new Double((1 + .1) / (10 + 4 * 10));
   aryNumbers[8][1] = new Double((6 + .1) / (10 + 4 * 10));
   aryNumbers[8][2] = new Double((2 + .1) / (10 + 4 * 10));
   aryNumbers[8][3] = new Double((1 + .1) / (10 + 4 * 10));             
}

但是我一直在得到一个ArrayIndexOutOfBoundException:4围绕数组[4] [0]。

2 个答案:

答案 0 :(得分:0)

查看你的数组声明:

new double[4][8]

数组的第一个维度只有4个元素。因此,当您尝试访问第5个元素时出现错误:

aryNumbers[4][0]

事实上,您的代码是尝试通过第9个元素一直访问

aryNumbers[8][0]

从它的外观来看,你可能意味着来声明这样的数组:

new double[9][4]

答案 1 :(得分:0)

当“位置”(4)上有四个条目时,您无法使用索引new double[4][8]。在这种情况下,最左侧的索引可以是0123