在Java中使用零作为整数打印的对角线

在Java中使用零作为整数打印的对角线,java,Java,我的代码有问题。我正在制作一个程序,它应该显示如下: 0 2 3 4 5 0 7 8 9 10 0 11 12 13 14 0 0 1 1 1 2 0 2 2 3 3 0 3 4 4 4 0 这是我的密码: int rows = 4, count1=1, count2=4; for(int i=1; i<=rows; i++){ for(int j=1; j<=rows; j++){ if(j==count1){

我的代码有问题。我正在制作一个程序,它应该显示如下:

0 2 3 4 
5 0 7 8
9 10 0 11
12 13 14 0
0 1 1 1
2 0 2 2
3 3 0 3
4 4 4 0
这是我的密码:

int rows = 4, count1=1, count2=4;

    for(int i=1; i<=rows; i++){
        for(int j=1; j<=rows; j++){
            if(j==count1){
                System.out.printf("0");
            }else{
                System.out.print(count1);
            }
        }
        if(i<=rows){
            count1++;
            count2--;
        }
        System.out.printf("\n");
    }
谁能告诉我我的代码有什么问题吗?谢谢

使用计数器(例如,下面给出的代码中的
计数
)以
1
初始化以打印值。当
i==j
时打印
0
。无论是打印计数器值还是
0
,都要增加计数器

按如下方式操作:

public class Main {
    public static void main(String[] args) {
        int rows = 4, count = 1;

        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= rows; j++, count++) {
                if (i == j) {
                    System.out.printf("%3d", 0);
                } else {
                    System.out.printf("%3d", count);
                }
            }
            System.out.printf("\n");
        }
    }
}
使用初始化为
1
的计数器(如下面给出的代码中的
count
)打印值。当
i==j
时打印
0
。无论是打印计数器值还是
0
,都要增加计数器

按如下方式操作:

public class Main {
    public static void main(String[] args) {
        int rows = 4, count = 1;

        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= rows; j++, count++) {
                if (i == j) {
                    System.out.printf("%3d", 0);
                } else {
                    System.out.printf("%3d", count);
                }
            }
            System.out.printf("\n");
        }
    }
}

我看不出需要两个柜台。在内部循环的每次迭代中递增
count1
。如果(j==i)我看不出需要两个计数器,则将第一个条件替换为
。在内部循环的每次迭代中递增
count1
。将第一个条件替换为
如果(j==i)

count1
您打印的内容应该在内部循环中递增。为什么不跳过
11
而跳过
6
呢?要解决问题,请考虑何时需要递增
count1
。用文字说明何时应该发生这种情况。还有,为什么您有
count2
?它似乎没有用于任何用途。请设置一些断点并启动调试器。通过这种方式,您将学到比这样问更多的东西。
count1
您打印的内容应该在内部循环中递增。为什么不跳过
11
,而跳过
6
呢?要解决您的问题,请考虑何时需要递增
count1
。用文字说明何时应该发生这种情况。还有,为什么您有
count2
?它似乎没有用于任何用途。请设置一些断点并启动调试器。那样的话,你会学到更多的东西,而不仅仅是这样问。