我试图从文本中读取 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 1 1 1 :这是一行。您正在尝试用 Integer 解析它,但这一行不完全是整数,因为它包含空格也是字符。
要获取大小,您可以执行以下操作:
String line = br.readLine();
InputGraph.size = (line.size()+1)/2;
因为如果一行有 x 个整数,它将有 x-1 个空格(考虑到两个整数之间只有一个空格),因此,2x -1 = 行的大小。
关于java - 我如何从 inp 文本读取 adjMatrix 图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39647607/