简体   繁体   中英

Read file.txt and split (:)

I have file txt with format like this

Nama: John
Biologi: 8
Kimia: 9
Fisika: 10

Nama: Peter
Biologi: 10
Kimia: 8
Fisika: 7

Nama: Steve
Biologi: 8
Kimia: 9
Fisika: 6

I try to read it with buffer reader but it wont show anything when i print out, i want to get the value and store it into arraylist of string here is my try.....

try{
        File database = new File(file);
        FileReader fileInput = new FileReader(database);
        BufferedReader in = new BufferedReader(fileInput);
        String line = in.readLine();
        String[] data;
        while (line != null){
            data = line.split(":");
            list_Siswa.add(data);
            line = in.readLine();
        }
       String datas = "";
       for (String[] dataSiswa : list_Siswa){//for each to print data into variable
           datas += "\nNama: " + dataSiswa[0] + "\n" +
                   "Kimia: " + dataSiswa[1] + "\n" +
                   "Biologi: " + dataSiswa[2] + "\n" +
                   "Fisika: " + dataSiswa[3] + "\n";
       }
       System.out.println(datas);
        in.close();
    }catch (Exception e){
        System.out.println(e);
   }

java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2 (That is the error i get)

i'm trying the excat format to be print out as the file

You add each line to the variable list_Siswa . So for instance the first element of list_Siswa will be ["Nama"," John"] , and so data_Siswa[0] equals "Nama" and data_Siswa[1] equals " John" . Then data_Siswa[2] throws an error, because there is no such element in the array.

The code isn't smart enough to see Nama: John and assume the following lines are grades that should be associated with John. If you want that, you'll have to do it yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM