Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 打印4行4列不带数组的整数_Java - Fatal编程技术网

Java 打印4行4列不带数组的整数

Java 打印4行4列不带数组的整数,java,Java,我应该创建一个程序,打印出以下内容: 1 5 9 13 2 6 10 14 3 7 11 15 4 8 12 16 1 5 9 13 2 6 10 14 3 7 11 15 4 8 12 16 以下是我当前的代码: int n = 1, cols = 4, rows = 4; for (int i = 1; i <= rows; i++) { for (int j = 1; j <= cols; j

我应该创建一个程序,打印出以下内容:

1 5 9  13
2 6 10 14
3 7 11 15
4 8 12 16
1   5   9   13  
2   6   10  14  
3   7   11  15  
4   8   12  16
以下是我当前的代码:

int n = 1,
    cols = 4,
    rows = 4;

for (int i = 1; i <= rows; i++) {
    for (int j = 1; j <= cols; j++) {
        System.out.print(n+" ");
        n++;
    }
    System.out.println();
}

有人能帮我找出解决这个问题的办法吗?我已经尝试了很多方法,但就是不能得到正确的输出。无论如何,谢谢。

将内部循环从0改为cols-1,而不是1改为cols,并使其打印外部循环变量+内部循环变量*4。

Java只能以行打印,不能以列打印。因此,您需要打印的第一行是:

1   5   9   13
换句话说,每一个连续的数字都比它前面的数字大4。因此,从第一行的第一个数字开始外循环,即1。现在,每行包含4个数字,因此内部循环需要迭代四次。请参阅以下代码:

int行=4; int cols=4; 对于int行=1;row这肯定会起作用:

for(int row=1, num; row<=4; row++)
{
    num = row;
    for(int col=1; col<=4; col++, num+=4)
    {
        System.out.print(num + " ");
    }
    System.out.println();
}
for(int row=1, num; row<=4; row++)
{
    num = row;
    for(int col=1; col<=4; col++, num+=4)
    {
        System.out.print(num + " ");
    }
    System.out.println();
}