我有一个二维数组,我希望通过JOptionPane显示。到目前为止,它一次向我显示一行。但我希望它能同时显示所有8行。
在运行代码后,它还在JOptionPane中显示括号和逗号。有没有办法摆脱那些括号和逗号?
到目前为止,这是我的代码,我刚开始学习Java。
package indzendopgave2;
import javax.swing.JOptionPane;
import java.util.Arrays;
public class Inzend2 {
public static void main(String[] args) {
//Creating array
int[][] blastTable = new int[][]{
{32,31,30,29,28,27,26,25},
{24,23,22,21,20,19,18,17},
{16,15,14,13,12,11,10,9},
{8,7,6,5,4,3,2,1},
{0,-1,-2,-3,-4,-5,-6,-7},
{-8,-9,-10,-11,-12,-13,-14,-15},
{-16,-17,-18,-19,-20,-21,-22,-23},
{-24,-25,-26,-27,-28,-29,-30,-31}
};
printArray(blastTable);
}
//Method to print two dimensional array in a JOptionPane
public static void printArray(int[][] num1){
for(int x=0; x<num1.length; x++){
String output = Arrays.toString(num1[x]);
JOptionPane.showMessageDialog(null, output, "Uitvoer",
JOptionPane.INFORMATION_MESSAGE);
}
}
}
答案 0 :(得分:2)
如果要一次显示整个数组,则根本不需要使用循环。
,
如果要删除[]
和<Image x:Name="img" Source= "D:\test.gif" />
,则必须将数组解析为字符串并根据需要对其进行格式化。
答案 1 :(得分:1)
这也可以
public static void printArray(int[][] num1) {
String output = "";
for (int x = 0; x < num1.length; x++) {
output += Arrays.toString(num1[x]) + "\n";
}
JOptionPane.showMessageDialog(null, output, "Uitvoer",
JOptionPane.INFORMATION_MESSAGE);
}
答案 2 :(得分:0)
使用最佳工具进行作业,并在Swing中显示表格数据,这意味着创建一个JTable。我将使用您的数据创建DefaultTableModel对象,将模型放入JTable,然后在JOptionPane中显示JTable。解决。
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import java.util.Arrays;
public class Inzend2 {
public static void main(String[] args) {
// Creating array
int[][] blastTable = new int[][] { { 32, 31, 30, 29, 28, 27, 26, 25 },
{ 24, 23, 22, 21, 20, 19, 18, 17 },
{ 16, 15, 14, 13, 12, 11, 10, 9 }, { 8, 7, 6, 5, 4, 3, 2, 1 },
{ 0, -1, -2, -3, -4, -5, -6, -7 },
{ -8, -9, -10, -11, -12, -13, -14, -15 },
{ -16, -17, -18, -19, -20, -21, -22, -23 },
{ -24, -25, -26, -27, -28, -29, -30, -31 } };
printArray(blastTable);
}
// Method to print two dimensional array in a JOptionPane
public static void printArray(int[][] num1) {
String[] columnNames = { "A", "B", "C", "D", "E", "F", "G", "H" };
// table models expect reference type data, and so
// int array must be changed to an Integer array
Integer[][] data = new Integer[num1.length][num1[0].length];
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
data[i][j] = num1[i][j];
}
}
DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
JOptionPane.showMessageDialog(null, scrollPane, "Uitvoer",
JOptionPane.INFORMATION_MESSAGE);
}
}