为什么我在下一行继续获得indexOutOfBOundException
0?:
rotatedShape[r][c] = shape[c][height-1-r];
方法rotateCW()
顺时针旋转char[][]
90度,但我不断收到错误。请问smb请看一下?谢谢!
public static void main(String[] args)
{
CreateShape temp = new CreateShape(10,10, 'a',
new char[][]{{'x','.','.'},
{'.','.','x'},
{'x','.','x'}},
"x . .\n"
+ ". . x\n"
+ "x . x");
temp.rotateCW();
System.out.println(temp);
}
public class CreateShape implements Shape {
private String tempLayout = "";
private String layout;
private int height;
private int width;
private char dc;
private Rotation initialPos;
private Rotation nextPos;
private char[][] shape;
private char[][] rotatedShape = new char[height][width];// = new char[shape.length][shape[0].length];
public CreateShape(int height, int width, char dc, char[][] charLayout, String layout)
{
this.height = height;
this.width = width;
this.dc = dc;
this.shape = charLayout;
this.layout = layout;
initialPos = Rotation.CW0;
}
public void rotateCW()
{
// String tempLayout = "";
nextPos = initialPos.next();
/*for(int r = 0; r < height; r++)
for(int c = 0; c < width; c++)
{
rotatedShape[c][height-1-r] = shape[r][c];
layout += rotatedShape[c][height-1-r];
}*/
for(int r = 0; r < height; r++)
for(int c = 0; c < width; c++)
{
rotatedShape[r][c] = shape[c][height-1-r];
tempLayout += rotatedShape[r][c];
}
}
}
答案 0 :(得分:0)
CreateShape temp = new CreateShape(10,10, 'a', new char[][]{{'x','.','.'},
{'.','.','x'},
{'x','.','x'}}, "x . .\n"
+ ". . x\n"
+ "x . x");
您传入的宽度和高度为10,但您的数组仅为3x3。然后根据宽度/高度10继续循环遍历3x3数组(shape
)。
for(int r = 0; r < height; r++)
for(int c = 0; c < width; c++)
{
rotatedShape[r][c] = shape[c][height-1-r];
tempLayout += rotatedShape[r][c];
}
}
10大于3.这显然会导致IndexOutOfBounds
例外。
答案 1 :(得分:0)
在你知道它的高度和宽度之前,你要实例化你的数组。具体来说,这三个声明正在打破你:
private int height;
private int width;
private char[][] rotatedShape = new char[height][width];
Java在构造时有一个关于未分配变量的特殊规则。如果未分配,they are assigned to an initial value。对于基元和boolean
,它分别为0和false
;对于对象,它是null
。
你在这里所做的是有效地创建一个大小(0,0)的数组,这就是为什么你在任何时候超出界限的索引。
我的直觉告诉我你不需要height
或width
字段。你要做的是声明rotatedShape
- 只是声明它,不要实例化它。
private char[][] rotatedShape;
在构造函数内部,当知道高度和宽度时,然后,然后才能正确实例化数组。
public CreateShape(int height, int width, char dc,
char[][] charLayout, String layout) {
this.dc = dc;
this.shape = charLayout;
this.layout = layout;
initialPos = Rotation.CW0;
rotatedShape = new char[height][width];
}