2016-09-22 85 views
1

我正在尝试从文本中读取adjMatrix图形,它只读取第一行,但是我遇到了这个错误。有什么建议吗?我怎样才能从inp文本中读取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 1 1 1:这是一条线。你试图用Integer来解析它,但是这行并不是完全的整数,因为它包含的空格也是字符。

为了得到大小,你可以做这样的事情:

String line = br.readLine(); 
    InputGraph.size = (line.size()+1)/2; 

因为如果行有X整数它将有X-1的空间(考虑到只有一个空间B/W两个整数)所以,2x -1 =行的大小。

+0

非常感谢你的回复,但我写它与同样的错误 –

+0

您可以发布更新后的代码,请与给还更新错误?因为我猜这个错误至少已经改变了。 –

0

您没有一行指定输入文件中图形中的顶点数。这就是为什么

InputGraph.size=Integer.parseInt(line); 

不起作用。 line这里包含"0 1 1 1",它不止一个整数。
您需要从第一行的整数中找到大小。此外,我也建议关闭输入文件读取它,使用最好的尝试,与资源后:

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(); 
} 
+0

非常感谢您的建议,但仍然InputGraph.adMatrix [i] [j] = Integer.parseInt(strArry [j]); java.lang.NumberFormatException:对于输入字符串:“” \t at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) –

+0

然后似乎有a)以空格开始的行或b)int与多个空格或c)输入文件中的空行......编辑答案 – fabian