我有一个文本文件,我必须将其存储到一个二维数组中,该数组具有 3 列和 numRecords 行,但它是在一个方法中实现的。参数 numRecords 是要从输入文件中读取的值的数量。我得到一个 InputMismatchException,我不知道为什么。任何帮助将不胜感激
public String[][] readFile(File file, int numRecords) throws IOException {
int numRows = numRecords;
int numColumns = 3; // column 1 will be age, column 2 will be height, column 3 will be weight
String[][] data = new String[numRows][numColumns];
try {
Scanner readFile = new Scanner(file);
String line = null;
line = readFile.nextLine().trim();
while (readFile.hasNextLine()) {
line = readFile.nextLine();
String[] str = line.split(",");
for (String element : str) {
element = element + " ";
for (int row = 0; row < data.length; row++) {
for (int column = 0; column < data[0].length; column++) {
data[row][column] = Integer.toString(readFile.nextInt());
data[row][column] = Integer.toString(readFile.nextInt());
data[row][column] = Integer.toString(readFile.nextInt());
}
}
}
}
readFile.close();
}
catch (InputMismatchException e1) {
e1.printStackTrace();
}
return data;
}
最佳答案
您正在通过读取行从您的扫描仪生成元素
。您还试图从扫描仪中读取 int(s) 并忽略您已读取的元素。另一个可能的问题是您的代码在开始之前没有测试文件是否可以实际读取。而且我更喜欢 try-with-Resources
而不是显式关闭 Scanner
(因为这里只要有异常就会泄漏文件句柄)。另外,为什么读取 int(s) 并将它们转换为 String
- 我更喜欢读取 int[][]
。把这些放在一起,
public int[][] readFile(File file, int numRows) throws IOException {
if (!file.exists() || !file.canRead()) {
System.err.printf("Cannot find file: %s%n", file.getCanonicalPath());
return null;
}
int numColumns = 3;
int[][] data = new int[numRows][numColumns];
try (Scanner readFile = new Scanner(file)) {
while (readFile.hasNextLine()) {
String line = readFile.nextLine();
String[] tokens = line.split(",");
int row = 0, column = 0;
for (String element : tokens) {
if (column >= numColumns) {
column = 0;
row++;
}
data[row][column] = Integer.parseInt(element);
column++;
}
}
} catch (InputMismatchException e1) {
e1.printStackTrace();
}
return data;
}
关于java - 方法 : Taking a text file and storing it in 2d array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57734539/