kix*_*kix 14 java arrays format text
我有二维数组的问题.我有这样的显示:
1 2 3 4 5 6 7 9 10 11 12 13 14 15 16 . . . etc
Run Code Online (Sandbox Code Playgroud)
基本上我想要的是显示它显示为:
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20
21 22 23 24 ... etc
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
int twoDm[][]= new int[7][5];
int i,j,k=1;
for(i=0;i<7;i++){
for(j=0;j<5;j++) {
twoDm[i][j]=k;
k++;}
}
for(i=0;i<7;i++){
for(j=0;j<5;j++) {
System.out.print(twoDm[i][j]+" ");
System.out.print("");}
}
Run Code Online (Sandbox Code Playgroud)
dje*_*lin 13
您需要在每行之后打印一个新行... System.out.print("\n"),或者使用println等.就目前而言,您只需打印任何内容 - System.out.print(""),替换print为println或""使用"\n".
Mar*_*vic 12
如果你不介意逗号和括号,你可以简单地使用:
System.out.println(Arrays.deepToString(twoDm).replace("], ", "]\n")));
Run Code Online (Sandbox Code Playgroud)
Tho*_*orn 11
您可以编写一个方法来打印像这样的二维数组:
//Displays a 2d array in the console, one line per row.
static void printMatrix(int[][] grid) {
for(int r=0; r<grid.length; r++) {
for(int c=0; c<grid[r].length; c++)
System.out.print(grid[r][c] + " ");
System.out.println();
}
}
Run Code Online (Sandbox Code Playgroud)
And*_*son 10
public class FormattedTablePrint {
public static void printRow(int[] row) {
for (int i : row) {
System.out.print(i);
System.out.print("\t");
}
System.out.println();
}
public static void main(String[] args) {
int twoDm[][]= new int[7][5];
int i,j,k=1;
for(i=0;i<7;i++) {
for(j=0;j<5;j++) {
twoDm[i][j]=k;
k++;
}
}
for(int[] row : twoDm) {
printRow(row);
}
}
}
Run Code Online (Sandbox Code Playgroud)
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 32 33 34 35
Run Code Online (Sandbox Code Playgroud)
当然,你可以像其他答案中提到的那样交换7和5,每行7个.