我目前正在制作一个以用户设置的数字开始的拉丁方块,但为了简单起见,我将排除扫描仪代码。
public static void main(String[] args){
int first = 2; // starting integer on square
int order = 4; //max integer
String space = new String(" ");
for (int row = 0; row < order; row++)
{
for (int column = 0; column < order; column++)
{
for (int shift = 0; shift < order; shift++)
{
int square = ((column+(first-1)) % order + 1); //this makes a basic square with no shifting
int latin = square+shift; //this is where my code becomes a mess
System.out.print(latin + space);
}
System.out.println();
}
}
}
}
输出:
2 3 4 5
3 4 5 6
4 5 6 7
1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7
1 2 3 4
它是如此接近,考虑到它确实从我预先确定的第一个数字开始,它只打印4个整数。我遇到的问题是它比我的顺序整数走得更远而且它打印了两倍的行。知道我该怎么做吗?
作为参考,这就是我想要它打印的内容:
2 3 4 1
3 4 1 2
4 1 2 3
1 2 3 4
似乎最内层循环for (int shift...)
是冗余的,它造成了输出的重复,latin
的值应该用row
参数来计算:
public static void main(String args[]) {
int first = 2; // starting integer on square
int order = 4; //max integer
String space = " ";
for (int row = 0; row < order; row++) {
for (int column = 0; column < order; column++) {
int latin = (row + column + first - 1) % order + 1;
System.out.print(latin + space);
}
System.out.println();
}
}
输出:
2 3 4 1
3 4 1 2
4 1 2 3
1 2 3 4