我創建了一個名爲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!");
}
}
}
你從哪裏找到這段代碼? –
我發現它在http://introcs.cs.princeton.edu/java/14array/MagicSquare.java.html ,但我稍微調整了它.. –
我編輯它以顯示我創建的完整代碼。 –