有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java从txt文件中读取数字并将其写入2d数组

我的目标是从txt文件中读取数据,并将其放入2d数组中。给我带来问题的代码是:

    Scanner input = new Scanner(new FileReader(file));

    //save the number of vertex's
    vCount = input.nextInt();

    //create a 2d array
    Integer[][] adjList = new Integer[vCount][vCount];

    String line;
    String [] arrLn;

    for (int i = 0; i < vCount; i++) {

        line = input.nextLine(); //the value of 'line' never changes
        arrLn = line.split(" ");

        for (int j = 0; j < vCount; j++) {
            adjList[i][j] = Integer.parseInt(arrLn[j]); //errors list problem is here
        }
    }

示例txt文件如下:

5
1 2 3 4
2 3
3 1 2
4 1 4
5 2 4

其中第一行是顶点数,其余行是要插入数组的数据。需要插入它们,以便txt文件中的每一行都保留在数组中自己的行中(即:数组第1行中的元素不能等于'1,2,3,4,2,3',而是'1,2,3,4'

我一辈子都无法理解为什么line变量实际上不读取这行。我在运行代码时没有发现任何错误

收到错误:

run:
Enter the File Name
C:\Users\YAZAN\Desktop\test.txt
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:504)
at java.lang.Integer.parseInt(Integer.java:527)
at dbsearchs.Graph.runBFS(Graph.java:38)
at dbsearchs.Driver.main(Driver.java:24)
Java Result: 1
BUILD SUCCESSFUL (total time: 26 seconds)

共 (1) 个答案

  1. # 1 楼答案

    首先,你真的确定line的值永远不会改变吗

    其次,可能会出现问题,因为您调用了first input。然后输入。nextLine()。尝试执行输入。用nextLine()代替nextInt(),并从该行获取您的号码。目前,您第一次调用input。nextLine()很可能会让第一行剩下的内容一无所获

    第三,我相信在运行程序时,一旦NumberFormatException被修复,就会出现ArrayIndexOutOfBounds异常。在第二个循环中,不要循环到vCount,而是循环到arrLn。而是长度