我需要将2D char数组的内容转换为字符串,并用边框包围它。无论采用何种方法,每个方框都会有所不同。每当我运行客户端时,我在第107行(在代码中标记)得到错误java.lang.ArrayIndexOutOfBoundsException:4,我不知道为什么。关于什么是错的任何想法?
public class TwoDArrayFiller
{
private char [][] array;
public TwoDArrayFiller(char[][] dataArray)
{
array = new char[dataArray.length][dataArray[0].length];
for(int i = 0; i < dataArray.length ; i++ )
{
for( int j = 0; j < dataArray[0].length ; j++ )
{
array[i][j] = dataArray[i][j];
}
}
} //end constructor
public void fillRows()
{
for ( int i = 0; i < array.length ; i+=2 )
{
for( int j = 0; j < array[i].length; j++ )
{
array[i][j] = 'X';
}
}
} // end fillRows
public void fillColumns()
{
for( int i = 0; i < array.length; i++ )
{
for (int j = 0; j < array[0].length; j+=2 )
{
array[i][j] = 'X';
}
}
} // end fillcolumns
public void border()
{
for( int i = 0; i < array.length; i++ )
{
for( int j = 0; j < array[0].length; j++ )
{
if ( i == 1 || i == 2 )
{
array[i][j] = 'X';
j+=2;
}
else
{
array[i][j] = 'X';
}
}
}
}// end border
public String toString()
{
String output = new String();
for( int i = 0; i < array.length + 2; i++ )
{
for( int j = 0; j < array[0].length + 2; j++ )
{
if( ( i == 0 && j == 0 ) || (i == 0 && j == ( array[0].length + 2 )) )
{
output = output + "+";
if ( j == ( array[0].length + 2 ) )
output = output + "\n";
}
else if( i == ( array.length + 2 ) && j == 0 )
{
output = output + "+";
}
else if( ( i == 0 && j == ( array[0].length + 2 ) ) || ( i == 5 && j == ( array[0].length + 2 ) ))
{
output = output + "+\n";
}
else if ( i == 0 || i == ( array[0].length + 2 ) )
{
output = output + "-";
}
else if( j == 0 || j == ( array[0].length + 2 ) )
{
output = output + "|";
if( j == ( array[0].length + 2 ) )
{
output = output + "\n";
}
else{
}
}
else
{
output = output + array[i - 1][j - 1]; // here is where the error occurs
}
}
}
return output;
}// end tostring
}
答案 0 :(得分:2)
这是我要改变的事情:
for( int i = 0; i < array.length + 2; i++ )
array.length + 2表示你想在数组之外“指向”
答案 1 :(得分:2)
在你的陈述中:
else
{
output = output + array[i - 1][j - 1];
}
你正在访问数组[i-1] [j-1],但是你已经说过我可以上传到array.length + 2,这个指向数组[array.length + 1],这就是超出范围。
答案 2 :(得分:1)
在toString函数中,你的i可以达到array.length + 1,但随后 array [i-1]将超出范围,但在else子句中,您访问数组[i-1] [j-1]。吊杆!