您好,我试图在查看双数组后弄清楚:
public static String returnWhatIsInTheArrayAsAString(char [][] a){
String whatIs = " ";
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a[i].length; j++){
}
}
return whatIs + "\n";
}
如果有意义,我如何返回两个数组中的内容?如何将其添加到我的\ n?
答案 0 :(得分:1)
假设我正确理解你的问题,你有char [] [],你基本上就像一个字符串数组,你想要返回一个字符串,每个成员的数组由一个新行字符分隔?然后它相对简单。
public static String returnWhatIsInTheArrayAsAString(char [][] a){
StringBuilder whatIs = new StringBuilder();
for(int i = 0; i < a.length; i++){
whatIs.append(new String(a[i])).append('\n');
}
return whatIs.toString();
}
}
如果你想要的是将数组的内容作为一个字符串返回,那么可能是:
public static String returnWhatIsInTheArrayAsAString(char[][] a) {
StringBuilder whatIs = new StringBuilder();
for (int i = 0; i < a.length; i++) {
whatIs.append('{ ');
for (int j = 0; j < a[i].length; j++) {
whatIs.append(a[i][j]);
if(j < a[i].length - 1){
whatIs.append(', ');
}
}
whatIs.append(' }\n');
}
return whatIs.toString();
}
会做到这一点。
答案 1 :(得分:0)
您可以在循环播放时将字符添加到字符串中:
public class Test {
public static String returnWhatIsInTheArrayAsAString(char [][] a){
String whatIs = " ";
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a[i].length; j++){
whatIs += a[i][j];
}
whatIs += "\n";
}
return whatIs + "\n";
}
public static void main(String[] args) throws Exception {
char[][] foo = new char[][] {{'a', 'b', 'c'}, {'d', 'e', 'f'}, {'g', 'h', 'i'}};
System.out.println(returnWhatIsInTheArrayAsAString(foo));
}
}
答案 2 :(得分:0)
使用foreach
和new String(char[] value)
作为行。
public static String returnWhatIsInTheArrayAsAString(char[][] array) {
String string = "";
for (char[] row : array) {
string += new String(row) + "\n";
}
return string;
}
样本用法:
public static void main(String[] args) throws InterruptedException {
char[][] foo = new char[][] {{'a', 'b', 'c'}, {'d', 'e', 'f'}, {'g', 'h', 'i'}};
System.out.println(returnWhatIsInTheArrayAsAString(foo));
}
将返回
abc
def
ghi