有人可以向我解释第二个 for 循环 ..我已经理解了第一个 ..谢谢
Can someone explain to me the 2nd for loop .. I already understand the first one.. thanks
我正在创建一个名为 magicsquare 的 java 项目,我在网上搜索了如何创建它。现在,我试图了解第二个循环是如何工作的,我知道它打印并对齐幻方,但我不知道细节。我已经知道第一个了。如果有人向我解释第二个循环,我将不胜感激。谢谢!
import java.util.*;
public class Magicsquare {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
try{
int N;
System.out.print("Enter a number to create a Magic Square: ");
N=input.nextInt();
if (N % 2 == 0){
System.out.print("N must be an Odd number!");
}
else{
int[][] magic = new int[N][N];
int row = N-1;
int col = N/2;
magic[row][col] = 1;
for (int i = 2; i <= N*N; i++) {
if (magic[(row + 1) % N][(col + 1) % N] == 0) {
row = (row + 1) % N;
col = (col + 1) % N;
}
else {
row = (row - 1 + N) % N;
}
magic[row][col] = i;
}
for (int c = 0; c < N; c++) {
for (int r = 0; r < N; r++) {
if (magic[r][c] < 10) System.out.print(" "); // for alignment
if (magic[r][c] < 100) System.out.print(" "); // for alignment
System.out.print(magic[r][c] + " ");
}
System.out.println();
}
}main (null);
}catch (Exception e){
System.out.print("Invalid Input!");
}
}
}
好吧,首先是显而易见的。关于 < 10
和 < 100
的部分:如果一个数字介于 0 和 9 之间,它只会打印出一位数字。如果它在 10 到 99 之间,它将打印出两个。如果它在 100 到 999 之间,它将使用三位数字打印出来。 (写这段代码似乎是假设它只会遇到0到999之间的数字。一般来说,最好以某种方式确保而不是希望。)
因此,使用 if
语句及其额外的空格,“5”将打印为“5”(注意两个前导空格总共三个字符)。 25 将打印为“25”(同样是三个字符),而 125 将打印为“125”(同样是三个数字)。由于所有数字都使用三个字符打印出来,因此所有内容都将整齐地排列在列中。
让我感到困惑的是,您首先迭代 c
,然后 r
。这似乎是说您在屏幕上的一行中打印出第一列,然后将第二列打印为第二行,将第三列打印为第三行。 IE。整个东西在对角线上旋转。但也许这只是一个命名问题。
我正在创建一个名为 magicsquare 的 java 项目,我在网上搜索了如何创建它。现在,我试图了解第二个循环是如何工作的,我知道它打印并对齐幻方,但我不知道细节。我已经知道第一个了。如果有人向我解释第二个循环,我将不胜感激。谢谢!
import java.util.*;
public class Magicsquare {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
try{
int N;
System.out.print("Enter a number to create a Magic Square: ");
N=input.nextInt();
if (N % 2 == 0){
System.out.print("N must be an Odd number!");
}
else{
int[][] magic = new int[N][N];
int row = N-1;
int col = N/2;
magic[row][col] = 1;
for (int i = 2; i <= N*N; i++) {
if (magic[(row + 1) % N][(col + 1) % N] == 0) {
row = (row + 1) % N;
col = (col + 1) % N;
}
else {
row = (row - 1 + N) % N;
}
magic[row][col] = i;
}
for (int c = 0; c < N; c++) {
for (int r = 0; r < N; r++) {
if (magic[r][c] < 10) System.out.print(" "); // for alignment
if (magic[r][c] < 100) System.out.print(" "); // for alignment
System.out.print(magic[r][c] + " ");
}
System.out.println();
}
}main (null);
}catch (Exception e){
System.out.print("Invalid Input!");
}
}
}
好吧,首先是显而易见的。关于 < 10
和 < 100
的部分:如果一个数字介于 0 和 9 之间,它只会打印出一位数字。如果它在 10 到 99 之间,它将打印出两个。如果它在 100 到 999 之间,它将使用三位数字打印出来。 (写这段代码似乎是假设它只会遇到0到999之间的数字。一般来说,最好以某种方式确保而不是希望。)
因此,使用 if
语句及其额外的空格,“5”将打印为“5”(注意两个前导空格总共三个字符)。 25 将打印为“25”(同样是三个字符),而 125 将打印为“125”(同样是三个数字)。由于所有数字都使用三个字符打印出来,因此所有内容都将整齐地排列在列中。
让我感到困惑的是,您首先迭代 c
,然后 r
。这似乎是说您在屏幕上的一行中打印出第一列,然后将第二列打印为第二行,将第三列打印为第三行。 IE。整个东西在对角线上旋转。但也许这只是一个命名问题。