0

java を使用してファイルの最初の行を取得しようとしていますが、なぜそれが機能しないのか、なぜエラーが発生するのかわかりません。Javaでこれを試したのはこれが初めてです。

エラー

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 16
    at getSum.main(getSum.java:33)

コード

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.File;
import java.io.FileNotFoundException;
public class getSum {

    public static void main(String[] args) {
            File file = new File("path/InputArray.txt");
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            DataInputStream dis = null;
            String line = null;
            try{
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                dis = new DataInputStream(bis);

                while(dis.available() != 0){
                    line = dis.readLine();
                }
            }catch (FileNotFoundException e){
                e.printStackTrace();
            }catch (IOException e){
                e.printStackTrace();
            }
            String[] splitLine = line.split("\\s+");
            int[] numbers = new int[splitLine.length];

            for(int i = 0; i< line.length(); i++){
                try{
                    numbers[i] = Integer.parseInt(splitLine[i]);
                }catch(NumberFormatException nfe){};
            }


           int amount = 0;
           System.out.print(numbers.length);
           /*amount = sumArray(0,numbers.length,numbers.length,numbers);
           System.out.print("Total: " + amount);*/
    }
4

2 に答える 2

5

これを見てください:

int[] numbers = new int[splitLine.length];
for(int i = 0; i< line.length(); i++){
    try{
        numbers[i] = Integer.parseInt(splitLine[i]);
    }catch(NumberFormatException nfe){};
}

i0から...までを使用していline.length()ますが、これは。と同じではありませんsplitLine.length。私はあなたが意味したと思う:

for (int i = 0; i< splitLine.length; i++) {

その時点で、両方ともnumbers同じsplitLine長さであるため、間違いなく。を取得することはありませんArrayIndexOutOfBoundsException

于 2013-02-19T22:03:19.040 に答える
0

for ループの条件が間違っていると思います。splitLine.length() を確認する必要があると思います。

for(int i = 0; i< splitLine.length(); i++){
     try{
          numbers[i] = Integer.parseInt(splitLine[i]);
     }catch(NumberFormatException nfe){};
}
于 2013-02-19T22:04:38.433 に答える