我正在尝试读取与此类似的文本文件:
0000000000
0000100000
0001001000
0000100000
0000000000
这是我的代码:
public static int[][] readBoard(String fileName) throws FileNotFoundException {
File life = new File(fileName);
Scanner s = new Scanner(life);
int row = s.nextInt();
int columns = s.nextInt();
int [][] size = new int [row][columns];
for (int i=0; i <= row; i++) {
String [] state = new String [columns];
String line = s.nextLine();
state = line.split("");
for (int j=0; i <= columns; i++) {
size[i][j] = Integer.parseInt(state[j]);
}
}
return size;
}
它一直给我这个错误。我认为是 Integer.parseInt(state[j])
给我带来了麻烦,但我不知道为什么。
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at Project5.readBoard(Project5.java:33)
at Project5.main(Project5.java:9)
答案 0 :(得分:0)
我已经使用示例输入执行了您的代码,并且您在代码中存在逻辑问题。使用示例输入,代码甚至没有到达 parseInt()
行,在那里可以抛出所询问的 NumberFormatException
。我假设您已经在不同的输入中尝试过您的代码。异常消息是 staithforward,您试图将空字符串解析为数字。这是典型的NumberFormatException
。 parseInt()
函数可能会抛出异常,因此您的代码必须为此做好准备。
另一个问题是算法中的基本逻辑问题。您的 row
和 column
变量将填充文本中第一个到整数的标记。根据示例输入,第一个整数标记将是第一行 0000000000
,其整数值为 0
,第二个标记是 0000100000
,它将被解析为 100000
。所以你试图用这些维度初始化一个数组,这是不可能的。
要计算行数,您必须逐行读取文件。要获得列数,您可以检查行的长度。 (又可以开新题了,你想怎么处理格式不正确的输入文件,因为文件中的行长是多种多样的。)
这意味着如果您已经遍历了文件内容,则只能确定板的尺寸。为了防止多次迭代,您应该使用动态集合而不是标准数组,如 ArrayList。
这意味着当您逐行读取文件时,您可以在一行中一个接一个地处理字符。在此步骤中,您应该考虑文件末尾的无效字符和潜在的空字符。在此迭代期间,可以构建最终集合。
这个例子展示了一个潜在的解决方案:
private static int processCharacter(char c) {
try {
return Integer.parseInt((Character.toString(c)));
} catch (NumberFormatException e) {
return 0;
}
}
public static List<List<Integer>> readBoard(String fileName) throws FileNotFoundException {
List<List<Integer>> board = new ArrayList<>();
File file = new File(fileName);
FileReader fr = new FileReader(file);
try (BufferedReader br = new BufferedReader(fr)) {
String line;
while ((line = br.readLine()) != null) {
line = line.trim(); // removes empty character from the line
List<Integer> lineList = new ArrayList<>();
if(line.length() > 0) {
for (int i = 0; i < line.length(); i++) {
lineList.add(Main.processCharacter(line.charAt(i)));
}
board.add(lineList);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return board;
}