0

これは以下の私のコードです。java.lang.IndexOutOfBoundsExceptionが発生し、修正できませんか?ファイルに100を超える名前があるので、エラーが発生しないようにする必要があります。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ArrayPractice1 {
    public static void main(String[] args) throws FileNotFoundException
    {

        String[] names = new String[100];
        Scanner scan = new Scanner(new File("names.txt"));
        int index = 0;

        while (scan.hasNext()){
            names[index]=(scan.nextLine());
            index++;
        }     
        for(int i = 0; i <index -1; i++){
            System.out.println(names[i]);
        }

    }

}
4

5 に答える 5

2

youre not working with an ArrayList of Strings, you're working with a plain array of Strings. seems like youre getting more than 100 items from scan.hasNext() and so you eventually try to access names[100] and get the exception you describe
instead, you could use this:

ArrayList<String> names = new ArrayList<String>();

and then

while (scan.hasNext()){
   names.add(scan.nextLine());
} 

and you wont have to worry about knowing the exact size beforehand

于 2013-01-10T18:40:42.790 に答える
1

If the size of the input is not known at compile time, consider using an ArrayList instead of an array.

Just add the elements to the ArrayList using names.add(scan.nextLine()):

ArrayList<String> names = new ArrayList<String>();
while (scan.hasNext()) {
      names.add(scan.nextLine())
}
于 2013-01-10T18:40:54.777 に答える
0

Why not making it independent from any upper limit? Use an ArrayList:

    ArrayList<String> names = new ArrayList<String>();
    Scanner scan = new Scanner(new File("names.txt"));

    while (scan.hasNext()){
        names.add(scan.nextLine());
    }     
    for(String name : names){
        System.out.println(name);
    }
于 2013-01-10T18:42:06.047 に答える
0

配列のサイズとして100を指定しています.ファイルに100行を超える行がある場合、間違いなく例外がスローされます

于 2013-01-10T18:40:23.867 に答える
0

while ループの条件を次のように変更します。

while (scan.hasNext() && index < 100)

これにより、配列がいっぱいになった後に読み取りループが停止します

于 2013-01-10T18:40:26.570 に答える