简体   繁体   English

读取 file.txt 并拆分 (:)

[英]Read file.txt and split (:)

I have file txt with format like this我有像这样格式的文件txt

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.....我尝试使用缓冲区阅读器读取它,但是当我打印出来时它不会显示任何内容,我想获取该值并将其存储到字符串的 arraylist 中,这是我的尝试.....

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) java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2 (这是我得到的错误)

i'm trying the excat format to be print out as the file我正在尝试将 excat 格式打印为文件

You add each line to the variable list_Siswa .您将每一行添加到变量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" .因此,例如list_Siswa的第一个元素将是["Nama"," John"] ,因此data_Siswa[0]等于"Nama"并且data_Siswa[1]等于" John" Then data_Siswa[2] throws an error, because there is no such element in the array.然后data_Siswa[2]抛出错误,因为数组中没有这样的元素。

The code isn't smart enough to see Nama: John and assume the following lines are grades that should be associated with John.代码不够智能,无法看到Nama: John并假设以下几行是应该与 John 相关联的等级。 If you want that, you'll have to do it yourself.如果你想这样做,你必须自己做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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