实验环境:
- java: java 9.0.4
Java(TM) SE Runtime Environment (build 9.0.4+11)
Java HotSpot(TM) 64-Bit Server VM (build 9.0.4+11, mixed mode) - git: git version 2.16.1.windows.1
- IDE: intellij IDEA
实验要求:
part1:
检验一个矩阵是否为Magic Square:
- 每一行、每一列、两条对角线数字加和相等
- 每个数字必须为正整数
- 每一行的数字之间必须用‘\t’分割
给出5个文件 1.txt、2.txt、……5.txt,分别检验其是否为Magic Square,结果返回true或false;
part2:
public static boolean generateMagicSquare(int n) {
int magic[][] = new int[n][n];
int row = 0, col = n / 2, i, j, square = n * n;
for (i = 1; i <= square; i++) {
magic[row][col] = i;
if (i % n == 0)
row++;
else {
if (row == 0) row = n - 1;
else row--;
if (col == (n - 1)) col = 0;
else col++;
}
}
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++)
System.out.print(magic[i][j] + "\t");
System.out.println();
} return true;
}
实验思路:
part1:
- 用fileInput方法读入文件,并判断上述合法性的2、3点以及是否是一个矩阵(行、列数是否一致)
在该方法中,操作如下:
- 对file文件尝试读取,若读入为空则输出”File Null!“,并退出程序
- 每次读取一行,读取第一行后用string.spilt(”\t“)对该行进行分割,形成字符串数组strings_first
- 获得strings_first.length记为n,默认为该矩阵列数,并实例化二位数组array
- 对strings_first中每一个字符串做正则表达式匹配判断是,否为正整数,若有非正整数则输出”not a Integer!“并退出
- 循环读完该文件并重复进行2、3、4操作,若某一行的数字数不等于n,则说明分隔符错误,输出”Se'parator error!“并退出
- 每读一次记录下行数m,在最后判断m和n是否相等,若不相等则输出”Matrix error!“并退出
static boolean fileInput(File file)
- 在isLegalMagicSquare方法中判断矩阵的每一行、每一列、两条对角线加和是否相等
static boolean isLegalMagicSquare(String fileName)
实验收获:
- 注释的使用,在自己的IDEA中已经设置完毕
- static的使用