gpt4 book ai didi

java - 为什么我的二维数组/矩阵打印错误?

转载 作者:行者123 更新时间:2023-12-01 09:47:28 28 4
gpt4 key购买 nike

为什么不像矩阵那样打印出来? (我的意思是并排。)*真的不知道两个维度数组和矩阵之间是否存在差异,因为我可以理解,对我来说似乎有相同的事情。

import java.util.Arrays;

public class test {
public static void main (String[] args){

int array[][] = {{4,5,6},
{6,8,9}};

int array1[][] = {{5,4,6},
{5,6,7}};

声明我的第一个数组有多少行和冒号。

    System.out.println("Number of rows = " +array.length);
System.out.println("Number of cols = " + array[0].length);

打印数组。

    int l = array.length;
int c = array[0].length;

System.out.println();

System.out.println("Print matrice : \n " );
for(int i=0; i<l; i++){
for(int j=0; j<c; j++){

System.out.println(" | " +array[i][j]+ " | ");
}
System.out.println(" \n");
}


}
}

打印结果:

Number of rows = 2
Number of cols = 3

Print matrice :

| 4 |
| 5 |
| 6 |


| 6 |
| 8 |
| 9 |

最佳答案

System.out.println 自动添加换行符。您可以将两个 print 语句更改为 System.out.print,或将其更改为:

for(int i=0; i<l; i++){
for(int j=0; j<c; j++){
System.out.print(" | " +array[i][j]+ " | ");
}
System.out.println();
}

System.out.println() 将添加换行符,而不需要额外的 \n。 (请注意,这也是矩阵行之间出现两个换行符的原因)。

关于java - 为什么我的二维数组/矩阵打印错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37867909/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com