Java 从 toString() 方法返回一个二维数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21011027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
return a 2d array from toString() method
提问by Impalerz
I'm having trouble return a string 2d array so that it will display in table form. Here's what i got:
我在返回一个字符串二维数组时遇到问题,以便它以表格形式显示。这是我得到的:
if i write this code, it will display the array on one single line.
如果我编写此代码,它将在一行上显示数组。
public String toString() {
return Arrays.deepToString(hidingPlaces);
}
And if i write this, i get no output.
如果我写这个,我就没有输出。
public String toString() {
String aString = "";
for(int row = 0; row < arrayName.length; row++) {
for(int col = 0; col < arrayName[row].length; col++) {
aString = " " + arrayName[row][col];
}
}
return aString;
}
Last one, when i initialize the array (every box) to ' ' (a space), i get 0000 as output instead of [ ]. Oh this is a char array btw. Please take a look at my problem. Thanks in advance.
最后一个,当我将数组(每个框)初始化为 ' '(一个空格)时,我得到 0000 作为输出而不是 []。哦,顺便说一句,这是一个字符数组。请看看我的问题。提前致谢。
采纳答案by Steve Sanbeg
I think you meant
我想你的意思是
aString += " " + arrayName[row][col];
As it is, you're overwriting the string in each iteration.
实际上,您在每次迭代中都覆盖了字符串。
回答by Alex
for(int row = 0; row < arrayName.length; row++) {
for(int col = 0; col < arrayName[row].length; col++) {
aString += " " + arrayName[row][col];
}
aString += "\r\n";
}
If you display it on the web form you could use <br>
instead of \r\n
.
如果您在网页上显示它的形式,你可以使用<br>
的替代\r\n
。
回答by Hrishikesh
Use a stringbuffer or a stringbuilder to concatenate your string object in the tostring method Your aString gets initialized again and again without concatenation Use stringbuffer.append here where aString should be a str in String buffer
使用 stringbuffer 或 stringbuilder 在 tostring 方法中连接您的字符串对象您的 aString 会一次又一次地初始化而不连接使用 stringbuffer.append 在这里 aString 应该是字符串缓冲区中的 str
Edit1
编辑 1
public String toString() {
StringBuffer aString = new StringBuffer();
for(int row = 0; row < arrayName.length; row++) {
for(int col = 0; col < arrayName[row].length; col++) {
aString.append(" " + arrayName[row][col]);
}
}
return aString.toString();
}