java - 将文件中的数据读入二维数组
问题描述
我需要读取一个带有魔方格式的文件:#
# # #
# # #
# # #
其中第一行表示正方形大小并使用文件值创建一个二维数组。
我设置了我的 readMatrix 方法来读取行,创建了一个正确大小的二维数组,并将每个值输入到它的正确位置。
private int[][] readMatrix(String fileName) throws
FileNotFoundException {
int n;
File file = new File(fileName);
Scanner fileScan = new Scanner(file);
String line = fileScan.nextLine();
Scanner lineScan = new Scanner(line);
n = lineScan.nextInt();
square = new int[n][n];
while (fileScan.hasNextLine()) {
line = fileScan.nextLine();
while (lineScan.hasNext()) {
for (int i = 0; i < n; i++) {
lineScan = new Scanner(line);
for (int j = 0; j < n; j++) {
square[i][j] = lineScan.nextInt();
}
}
}
}
fileScan.close();
lineScan.close();
return square;
public int[][] getMatrix() {
int[][] copy;
int n = square.length;
copy = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
copy[i][j] = square[i][j];
}
}
return copy;
然而,该程序的测试器显示了一个正确尺寸的幻方,但所有值均为 0,并且 getMatrix 方法失败(我假设是因为返回的正方形与文件正方形不匹配)。我尝试在 readMatrix 中的 for/while 循环周围(内部/外部)移动扫描仪对象,并尝试使用 parseInt/scan next 而不是 nextInt,但没有成功。我难住了。
解决方案
试试这个代码能够从 3 x 3 矩阵中显示 1 - 9。变量类型可以根据您的需要进行更改。为了方便起见,我使用了“char”。
private static char[][] finalmatrix;
public static void main(String[] args) throws Exception {
finalmatrix = readMatrix("File.txt");
// Output matrix.
for (int i = 0; i < finalmatrix.length ;i++) {
for (int j = 0; j < finalmatrix[i].length ;j++) {
System.out.print(finalmatrix[i][j] + " ");
}
System.out.println("");
}
}
private static char[][] readMatrix(String fileName) throws IOException {
File file = new File(fileName);
Scanner scan = new Scanner(file);
int countRow = 0;
int countColumn = 0;
List temp = new ArrayList();
while (scan.hasNextLine()) {
String line = scan.nextLine();
for (int i = 0; i < line.length(); i++) {
// Count the number of columns for the first line ONLY.
if (countRow < 1 && line.charAt(i) != ' ') {
countColumn++;
}
// Add to temporary list.
if (line.charAt(i) != ' ') {
temp.add(line.charAt(i));
}
}
// Count rows.
countRow++;
}
char[][] matrix = new char[countRow][countColumn];
// Add the items in temporary list to matrix.
int count = 0;
for (int i = 0; i < matrix.length ;i++) {
for (int j = 0; j < matrix[i].length ;j++) {
matrix[i][j] = (char) temp.get(count);
count++;
}
}
scan.close();
return matrix;
}
推荐阅读
- debugging - 如果条件命中两次,则在下面的 rust 代码中
- angular - angular-slickgrid 分组时隐藏总行数
- powershell - 通过 Invoke-Command 调用命令时 PowerShell 不一致
- angular - Angular - 模板仅显示属性时更新,但如果其中有函数则不更新
- codenameone - 代号一如何在标签中剪切长字符串
- eclipse - 骆驼csv显示列名
- python - 使用 Conda 和 Spyder 安装 OpenCV
- r - 使用 dplyr 根据列名更改数据框中的值?
- datatables - 表中的标签选择(rendered_html 与 filter_match_mode=exact)
- c++ - “节点”仅在一个源文件 C++ 中不明确