我试图在对角线上打印相应的数字,但我只能打印直接向下的数字。它打印出 2, 1, 7, 0, 5。但输出不会以对角线打印。有人可以帮我吗?
public class Main_diagonal {
public static void main(String[] args) {
int array1[][] = {
{2,3,1,5,0 },
{7,1,5,3,1 },
{2,5,7,8,1 },
{0,1,5,0,1 },
{3,4,9,1,5 }
};
for (int i=0; i<5; i++)
{
for (int j=0; j<=i;j++)
{
if(i==j){
System.out.println(array1[i][j]);
}
}
}
}
}
最佳答案
如果“在对角线上打印数字”意味着您需要让输出像这样对角显示:
2
1
7
0
5
然后,在不打印数字的时候,让内部循环打印空格。
for (int i=0; i<5; i++)
{
for (int j=0; j<=i;j++)
{
if(i==j) { //then print the number and a new line
System.out.println(array1[i][j]);
}
else {
System.out.print(" "); //pads the line with spaces otherwise
}
}
}
关于java - 如何打印数组中的某个数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30734252/