题目:
所谓魔方阵是指这样的矩阵,它的每一行、每一列和对角线之和均相等,要求打印1~25之间由自然数构成的魔方阵至当前目录下的t1.txt中。
解答:
Test类:
package Experiment_3.Question_2;
import java.io.*;
/*所谓魔方阵是指这样的矩阵,它的每一行、每一列和对角线之和均相等,要求打印1~25之间由自然数构成的魔方阵至当前目录下的t1.txt中。*/
public class Test {
public static void main(String[] args) {
String fileName = "src\\Experiment_3\\Question_2\\test\\t1.txt";
try {
BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
int[][] num;
num = new int[5][5];
int n = 25, i = 0, j = 2;
while(n > 0)
{
num[i][j] = n;
i++;
j--;
i = check(i);
j = check(j);
if(num[i][j] != 0)
{
j++;
j = check(j);
}
n--;
}
for(int p = 0; p < 5; p++)
{
for(int q = 0; q < 5; q++)
{
if(q != 0)
System.out.print(" ");
System.out.printf("%2d", num[p][q]);
String s = String.valueOf(num[p][q]);
out.write(s);
out.write(" ");
}
System.out.println();
out.newLine();
}
out.close();
System.out.println("Over write!");
}
catch (IOException ioe) {
System.out.println("Problem reading " + fileName);
}
}
public static int check(int x){
if(x >= 5)
x -= 5;
if(x < 0)
x += 5;
return x;
}
}
运行结果:
欢迎大家探讨