java toString()表示输出
我的代码中有一个bug,相信我,我已经多次运行调试来找出代码的错误,但无法理解错误所在。我必须输出2d Arraylist的内容。例如,如果我这样做:
Board<String> board = new Board<String>(-4,1,-2,3,"A");
System.out.println(board);
它向我输出以下内容:
| -2| -1| 0| 1| 2| 3|
+---+---+---+---+---+---+
-4 | A| A| A| A| A| A|
+---+---+---+---+---+---+
-3 | A| A| A| A| A| A|
+---+---+---+---+---+---+
-2 | A| A| A| A| A| A|
+---+---+---+---+---+---+
-1 | A| A| A| A| A| A|
+---+---+---+---+---+---+
0 | A| A| A| A| A| A|
+---+---+---+---+---+---+
1 | A| A| A| A| A| A|
+---+---+---+---+---+---+
但是,当我将第四个值3
更改为更大的数字,例如4
((-4,1,-2,4,"A")
)时,它会说:
java.lang.IndexOutOfBoundsException: Index: 6, Size: 6
我所有的构造函数都工作得很好,我假设错误在toString()
方法中。再一次,我试着调试了好几次,但仍然不能确定这里会出什么问题。smb能帮我吗?错误发生在toString()
方法内的这一行:
# 1 楼答案
增加每列的行数:
这也是为什么它适用于#rows>;=#列,但不适用于#行<#纵队
拔出我的黑板。在内部for循环之前获取(row++)作为变量,如
然后行动
走出外环
或者,这里是对整个类的一个建议(请注意,我只改进了索引访问。还有足够的空间进行进一步改进,例如字符串连接):
}