java - 我如何从 inp 文本读取 adjMatrix 图

标签 java file-io

我试图从文本中读取 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/

相关文章:

java - 如果 Stream 没有结果则抛出异常

c# - 将 C# 脚本解析为 Java

c++ - 从具有两列的文件加载二维数组

Python read() 似乎返回的数据少于它读取的数据

c - 用C语言制作fifo

java - 对对象列表进行排序

java - TestNG - 可用于单类/方法执行的测试/套件作用域变量

java - 查找数组的中值?

java - 有没有专有的java对象池库?

php - 什么更快? file_put_contents();打开();写入(); fclose();?