-3

私の目標は、txt ファイルからデータを読み取り、それらを 2 次元配列に配置することです。私に問題を与える私のコードは次のとおりです。

    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'.

行変数が実際に行を読み取らない理由を、私の人生では理解できません。そして、コードを実行しただけで、コードにエラーは発生しません。

エラーを受け取りました:

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)
4

1 に答える 1

2

まず第一に、 の値がline決して変わらないことを本当に確信していますか?

次に、最初に input.nextInt() を呼び出してから input.nextLine() を呼び出すため、問題が発生する可能性があります。nextInt() の代わりに input.nextLine() を実行して、その行から番号を取得してみてください。現在、input.nextLine() への最初の呼び出しでは、最初の行の残りの部分が返される可能性が高く、何も表示されません。

第三に、プログラムの実行時に NumberFormatException が修正されると、ArrayIndexOutOfBounds 例外が発生すると思います。2 番目のループでは、vCount までループするのではなく、arrLn.length までループします。

于 2013-09-14T00:56:10.537 に答える