我需要将 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
}