【发布时间】:2021-11-24 02:30:04
【问题描述】:
我目前正在制作一个以用户设置的数字开头的拉丁方格,但为简单起见,我将排除扫描仪代码。
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
【问题讨论】:
-
这与您的问题完全无关,但您应该知道
new String(" ")是多余且毫无意义的。" "已经是一个包含单个空格的String。new String(" ")创建一个具有相同内容的新字符串。由于String对象是不可变的,因此它们可以互换,因为它们具有相同的内容,因此您应该只使用String space = " ";。
标签: java nested-for-loop latin-square