3-2打印魔方阵至当前目录下的t1.txt中-Java

题目:

所谓魔方阵是指这样的矩阵,它的每一行、每一列和对角线之和均相等,要求打印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;
    }
}

运行结果: 

欢迎大家探讨

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值