[英]Print an array of object as an integer array
我有一个5x5
的对象数组,看起来像这样:
Spot@3c72f59f Spot@60dcc9fe Spot@222114ba Spot@16e7dcfd Spot@3d121db3
Spot@3b07a0d6 Spot@11a9e7c8 Spot@3901d134 Spot@14d3bc22 Spot@12d4bf7e
Spot@4c1d9d4b Spot@7b227d8d Spot@7219ec67 Spot@45018215 Spot@65d6b83b
Spot@d706f19 Spot@30b7c004 Spot@79efed2d Spot@2928854b Spot@27ae2fd0
Spot@29176cc1 Spot@2f177a4b Spot@4278a03f Spot@147ed70f Spot@61dd025
而不是这个数组,我想打印一个看起来像这样的数组:
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
到目前为止,我的代码如下所示:
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
world[i][j] = new Spot(i,j);
System.out.print(" " + world[i][j]);
}
System.out.println();
}
如何以我想要的方式完成打印5x5
数组,而不是使用Spot
对象? 先感谢您。
您只需覆盖Spot
class 的toString()
方法。
class Spot {
private int i;
private int j;
public Spot(int i, int j) {
this.i = i;
this.j = j;
}
@Override
public String toString() {
// whatever you want to print
return String.valueOf(0);
}
}
因为当您使用" " + world[i][j]
时,换句话说就是" " + world[i][j].toString()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.