有一些关于这些话题的内容,但这个问题稍微有点不同。
我只关注更大问题的一半。我相信你们中的许多人都知道魔方问题。
提示:
假设有一个文件,每行有数字,形成如所示的正方形。编写一个程序,将信息读入到一个二维int数组中。程序应确定矩阵是否为魔方阵。
工作解决方案:
public static int[][] create2DIntMatrixFromFile(String filename) throws Exception {
int[][] matrix = {{1}, {2}};
File inFile = new File(filename);
Scanner in = new Scanner(inFile);
int intLength = 0;
String[] length = in.nextLine().trim().split("\\s+");
for (int i = 0; i < length.length; i++) {
intLength++;
}
in.close();
matrix = new int[intLength][intLength];
in = new Scanner(inFile);
int lineCount = 0;
while (in.hasNextLine()) {
String[] currentLine = in.nextLine().trim().split("\\s+");
for (int i = 0; i < currentLine.length; i++) {
matrix[lineCount][i] = Integer.parseInt(currentLine[i]);
}
lineCount++;
}
return matrix;
}
public static boolean isMagicSquare(int[][] square) {
return false;
}
这是我(旧的)从文本文件读取信息到2D数组的代码:
public static int[][] create2DIntMatrixFromFile(String filename) throws Exception {
int[][] matrix = {{1}, {2}};
File inFile = new File(filename);
Scanner in = new Scanner(inFile);
in.useDelimiter("[/n]");
String line = "";
int lineCount = 0;
while (in.hasNextLine()) {
line = in.nextLine().trim();
Scanner lineIn = new Scanner(line);
lineIn.useDelimiter("");
for (int i = 0; lineIn.hasNext(); i++) {
matrix[lineCount][i] = Integer.parseInt(lineIn.next());
lineIn.next();
}
lineCount++;
}
return matrix;
}
public static boolean isMagicSquare(int[][] square) {
return false;
}
这里是我正在读取的文本文件。它是一个9x9的二维数组形状,但程序必须适应大小不确定的数组。
37 48 59 70 81 2 13 24 35
36 38 49 60 71 73 3 14 25
26 28 39 50 61 72 74 4 15
16 27 29 40 51 62 64 75 5
6 17 19 30 41 52 63 65 76
77 7 18 20 31 42 53 55 66
67 78 8 10 21 32 43 54 56
57 68 79 9 11 22 33 44 46
47 58 69 80 1 12 23 34 45
每行开头有两个空格是有意为之。
在我说明具体问题之前,这是一个作业模板,所以方法声明和变量初始化已经预先确定。
我不确定这个方法是否正确地从文件创建了一个二维数组,因为我还不能运行它。问题在于,由于某种原因,“matrix”只初始化了1列和2行。我不确定原因,但为了用文件中的数字填充数组,我需要创建一个二维数组,其维数等于一行中的值的数量。
我之前写过创建新的二维数组的代码。
int[line.length()][line.length()]
但是它创建了一个36x36的数组,因为每行有这么多个单独的字符。我有一种感觉,只需循环第一行,并通过计数器跟踪由零分隔的每个数字序列即可。对我来说,这个解决方案似乎太低效和耗时,仅仅是为了找到新数组的尺寸。最好的方法是什么?不使用ArrayLists,因为我必须在使用ArrayLists后重新编写此程序。
line.split(" ");
。 - ggmathur