我试图从文本中读取adjMatrix图,它只读取第一行但我遇到了这个错误。请问有什么建议吗?
java.lang.NumberFormatException: For input string: "0 1 1 1"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
public static void main(String[] args)throws IOException {
int row_num = 0;
//InputGraph gr = new InputGraph("input.txt");
// Cells w= gr.copyMatrix();
// w.printAdjMatrix();
try {
String fileName = ("input.txt");
File file = new File(fileName);
BufferedReader br = new BufferedReader(new FileReader(file));
//get number of vertices from first line
String line = br.readLine();
System.out.println("hi");
//InputGraph.size = Integer.parseInt(line.trim());
InputGraph.size=Integer.parseInt(line);
InputGraph.adMatrix = new int[InputGraph.size][InputGraph.size];
br.readLine();
for (int i = 0; i < InputGraph.size; i++) {
line = br.readLine();
String[] strArry = line.split(" ");
for (int j = 0; j < InputGraph.size; j++) {
InputGraph.adMatrix[i][j] = Integer.parseInt(strArry[j]);
if (Integer.parseInt(strArry[j]) == 1)
row_num++;
}
}
} catch (Exception e4) {
e4.printStackTrace();
}
输入文本文件
0 1 1 1
0 0 0 0
1 1 0 1
0 1 0 0
答案 0 :(得分:0)
0 1 1 1:这是一行。您正尝试使用Integer解析它,但此行不是完全整数,因为它包含空格也是字符。
要获得大小,您可以执行以下操作:
String line = br.readLine();
InputGraph.size = (line.size()+1)/2;
因为如果一行有x个整数,它将有x-1个空格(考虑到只有一个空格b / w两个整数)所以,2x -1 =行的大小。
答案 1 :(得分:0)
您没有一行指定输入文件中图表中的顶点数。这就是为什么
InputGraph.size=Integer.parseInt(line);
不起作用。 line
此处包含"0 1 1 1"
,它不只是一个整数
您需要从第一行中的整数中找到大小。此外,我建议在阅读后关闭输入文件,最好使用try-with-resources:
try (FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr)) {
String line = br.readLine();
String[] elements = line.trim().split(" +");
InputGraph.size=elements.length;
InputGraph.adMatrix = new int[InputGraph.size][InputGraph.size];
for (int i = 0; i < InputGraph.size; i++, line = br.readLine()) {
String[] strArry = line.trim().split(" +");
for (int j = 0; j < InputGraph.size; j++) {
InputGraph.adMatrix[i][j] = Integer.parseInt(strArry[j]);
if (InputGraph.adMatrix[i][j] == 1)
row_num++;
}
}
} catch (Exception e4) {
e4.printStackTrace();
}