使用Java读入一个TXT文件,文件中数据为字符串,数据之间使用空格隔开,n*n幻方,判断其行之和是否相等
时间: 2024-05-15 22:17:00 浏览: 71
java 判断两个文件是否相同
以下为Java代码实现:
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class MagicSquare {
public static void main(String[] args) {
int[][] square = readMagicSquare("magic_square.txt");
if (isMagicSquare(square)) {
System.out.println("This is a magic square.");
} else {
System.out.println("This is not a magic square.");
}
}
public static int[][] readMagicSquare(String filename) {
int[][] square = null;
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
String line = br.readLine();
int n = line.split(" ").length;
square = new int[n][n];
int i = 0;
while (line != null) {
String[] nums = line.split(" ");
for (int j = 0; j < n; j++) {
square[i][j] = Integer.parseInt(nums[j]);
}
line = br.readLine();
i++;
}
} catch (IOException e) {
e.printStackTrace();
}
return square;
}
public static boolean isMagicSquare(int[][] square) {
int n = square.length;
int sum = 0;
for (int i = 0; i < n; i++) {
sum += square[0][i];
}
// check row sum
for (int i = 1; i < n; i++) {
int rowSum = 0;
for (int j = 0; j < n; j++) {
rowSum += square[i][j];
}
if (rowSum != sum) {
return false;
}
}
// check column sum
for (int i = 0; i < n; i++) {
int colSum = 0;
for (int j = 0; j < n; j++) {
colSum += square[j][i];
}
if (colSum != sum) {
return false;
}
}
// check diagonal sum
int diagSum1 = 0;
int diagSum2 = 0;
for (int i = 0; i < n; i++) {
diagSum1 += square[i][i];
diagSum2 += square[i][n - 1 - i];
}
if (diagSum1 != sum || diagSum2 != sum) {
return false;
}
return true;
}
}
```
其中,`readMagicSquare`方法用于读取文件中的幻方数据,返回一个二维数组。`isMagicSquare`方法用于判断该二维数组是否为幻方,即每行、每列、每条对角线的和均相等。如果是幻方,则返回`true`,否则返回`false`。最后,在`main`方法中调用这两个方法,输出结果。
阅读全文