我正在尝试在对角线上打印相应的数字,但我只能直接打印数字。它打印出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]);
}
}
}
}
}
答案 0 :(得分:1)
我不确定您使用哪种语言,因此在当前状态下这可能对您不起作用,但您明白了。
一旦您显示了您正在使用的语言,我们就可以优化:)
String whitespace = "";
for (int i=0; i<5; i++)
{
System.out.println(whitespace + array1[i][i]);
whitespace += " ";
}
答案 1 :(得分:1)
如果通过&#34;在对角线上打印数字&#34;你的意思是你需要让输出像对角一样出现:
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
}
}
}
答案 2 :(得分:0)
像这样修改你的代码:
for (int i=0; i<5; i++)
{
for (int j=0; j<=i;j++)
{
if(i==j){
System.out.println(array1[i][j]);
break;
}
System.out.print(" ");
}
}