I have a matrix : 5x15 :
for(int i=0;i<5;i++){
for(int j=0;j<15;j++){
String[][] Matrix = { { "0", "0", "", "0", "5", "6", "", "", "55", "", "", "", "", "" }, { "1723", "0", "", "0", "0", "3", "", "", "2", "", "", "", "", "" },
开发者_运维知识库 { "10", "0", "", "0", "0", "0", "", "", "0", "", "", "", "", "" }, { "69", "0", "", "0", "0", "20", "", "", "100", "", "", "", "", "" },
{ "35", "0", "", "0", "15", "20", "", "", "57", "", "", "", "", "" } };
system.out.println(Matrix);
}}
and I need to print each line : line1,line2,..line5
final String[][] matrix = { { "0", "0", "", "0", "5", "6", "", "", "55", "", "", "", "", "" },
{ "1723", "0", "", "0", "0", "3", "", "", "2", "", "", "", "", "" },
{ "10", "0", "", "0", "0", "0", "", "", "0", "", "", "", "", "" },
{ "69", "0", "", "0", "0", "20", "", "", "100", "", "", "", "", "" },
{ "35", "0", "", "0", "15", "20", "", "", "57", "", "", "", "", "" } };
for (String[] row : matrix) {
System.out.println((Arrays.toString(row)));
}
Will produce the following output:
[0, 0, , 0, 5, 6, , , 55, , , , , ]
[1723, 0, , 0, 0, 3, , , 2, , , , , ]
[10, 0, , 0, 0, 0, , , 0, , , , , ]
[69, 0, , 0, 0, 20, , , 100, , , , , ]
[35, 0, , 0, 15, 20, , , 57, , , , , ]
Remove the system.out.println(Matrix);
and add at the end (outside the two loops):
for (int i = 0; i < matrix.length; ++i) {
System.out.println(Arrays.asList(matrix[i]));
}
Arrays are not printed readable, but collections like List are.
PS: by convention, variables start with lowercase, types and constants with uppercase
You could do something like
for (String[] row : matrix)
System.out.println(Arrays.toString(row));
To fix your code I suggest you move out the matrix declaration out of the loop, and add a print / println like this:
String[][] Matrix = {
{ "0", "0", "", "0", "5", "6", "", "", "55", "", "", "", "", "" },
{ "17", "0", "", "0", "0", "3", "", "", "2", "", "", "", "", "" },
{ "10", "0", "", "0", "0", "0", "", "", "0", "", "", "", "", "" },
{ "69", "0", "", "0", "0", "20", "", "", "10", "", "", "", "", "" },
{ "35", "0", "", "0", "15", "20", "", "", "57", "", "", "", "", "" }
};
for(int i=0;i<5;i++){
for(int j=0;j<14;j++){
if (j > 0)
System.out.print(", ");
System.out.printf("%2s", Matrix[i][j]);
}
System.out.println();
}
Output:
0, 0, , 0, 5, 6, , , 55, , , , ,
17, 0, , 0, 0, 3, , , 2, , , , ,
10, 0, , 0, 0, 0, , , 0, , , , ,
69, 0, , 0, 0, 20, , , 10, , , , ,
35, 0, , 0, 15, 20, , , 57, , , , ,
精彩评论