【发布时间】:2019-04-19 20:08:22
【问题描述】:
我正在尝试使用 JOptionPane 在消息对话框中打印出二维数组。我应该创建一个使用 for 循环将数组转换为字符串的方法。我已经尝试了很多,但它似乎没有让逻辑按我想要的那样工作。这是我目前所拥有的。
public static String toString(int[][] array) {
String res = "{";
for (int i = 0; i < array.length; i++) {
for (int j = 0; j <array[i].length; j++) {
res += array[i][j];
if(j < array.length-1) {
res += ",";
}
if (i < array.length-1) {
res += "}";
}
}
}res += "}";
return res;
}
主类:
import javax.swing.JOptionPane;
import arrays.Integer2dArrays;
public class Exercise4b {
public void testArray(int[][] array) {
String message = "";
message += "toString: " + Integer2dArrays.toString( array ) + "\n";
message += "elements: " + Integer2dArrays.elements( array ) + "\n";
message += "max: " + Integer2dArrays.max( array ) + "\n";
message += "min: " + Integer2dArrays.min( array ) + "\n";
message += "sum: " + Integer2dArrays.sum( array ) + "\n";
message += "average: " + String.format( "%1.2f", Integer2dArrays.average( array ) ) + "\n";
JOptionPane.showMessageDialog( null, message );
}
public static void main(String[] args) {
Exercise4b e4b = new Exercise4b();
int[][] test1 = {{1,2,3,4},{-5,-6,-7,-18},{10,9,8,7}};
int[][] test2 = {{1,2,3,4,5,6},{-7,-8,-9},{2,5,8,11,8},{6,4}};
e4b.testArray(test1);
e4b.testArray(test2);
}
}
最终结果应如下所示:
【问题讨论】:
-
目前的最终结果是什么样的?
-
您的代码仅在开头打印左括号。首先弄清楚何时在中间添加左括号
标签: java arrays methods tostring