2015-02-10 2 views
1

То, что я пытаюсь сделать, это добавить числа из .txt-файла и разбить его; в мой список ArrayListR2. На данный момент он работает полу, однако результат заключается только в том, что добавлен только последний счет из двух человек, оценка первого лица просто становится нулевой.
Это какая-то проблема с моим расколом?Разбиение arraylist и текстового файла

Любые идеи, как я получаю программу, чтобы написать все оценки?

+1

line.split ("[;]") выглядит странно? Вы действительно имели в виду это - расколоться на [;]? – mkrakhin

+0

@mkrakhin Регулярное выражение '" [;] "- это просто надуманный способ сказать' ';". – laune

ответ

0

Он пропускает строки (из файла) в вашем коде, потому что вы использовали

for (int i = 3; i < itemStudent.length; i++) { 
    String test = studin.readLine(); //<--- this is the error 
    listR2.add(test); 
} 

Вместо этого используйте

String test = itemStudent[i]; // to add the scores into the listR2 
0

Во-первых, ваш код:

BufferedReader studin = new BufferedReader(new FileReader(studentFile)); 
grader.Student student; 
student = new Student(); 
String line, eNamn, fNamn, eMail; 
ArrayList<String> listR = new ArrayList<String>(); 
ArrayList<String> listR2 = new ArrayList<String>(); 
//loop for the file and setters for first, lastname and email 
while ((line = studin.readLine()) != null) { 
    if (line.contains(";")) { 
     //# you don't need regex to split on a single specific character 
     String[] itemStudent = line.split("[;]"); 
     eNamn = itemStudent[0]; 
     fNamn = itemStudent[1]; 
     eMail = itemStudent[2]; 
     //#why are you using the Student object if you never use it in any way ? 
     //#also you are always updating the same "Student". if you expect to add it to say an ArrayList, 
     //#you need to declare a new student at the beginning of the loop (not outside of it) 
     student.setFirstName(fNamn); 
     student.setLastName(eNamn); 
     student.setEmail(eMail); 

     //Loop for the sum of the tests 
     Integer sum = 0; //# why Interger, the "int" primitive is more than sufficient 
     for (int index = 3; index < itemStudent.length; index++) { 
      try { 
       sum += Integer.parseInt(itemStudent[index]); 
       listR.add(itemStudent[index]); 
      } catch (Exception ex) {} //very bad practice, nerver silently drop exceptions. 
     } 
     //# that part is just wrong in many ways, I guess it's some left over debug/testing code 
     //# this also makes you skip lines as you will read as many lines as you have elements (minus 3) in itemStudent 
     /* 
     for (int i = 3; i < itemStudent.length; i++) { 
      String test = studin.readLine(); 
      listR2.add(test); 
     } 
     */ 
     System.out.println(eNamn + " " + fNamn + " " + eMail + " SUMMA:" + sum + " "); 
     //# you'll get a nice pointer address, but not it's values, you need to itterate the list to view it's content 
     System.out.println(listR2); 
    } 
} 

// # пометить мои комментарии и здесь быстрый пример отображения объектного подхода: (может содержать ошибки/недостающие импорт, но в остальном это должно быть хорошо, компилятор должен вам). чтобы запустить его: Java Main "your_file"

import java.util.ArrayList; 
import java.io.BufferedReader; 
import java.io.FileReader; 
import java.io.IOException; 
public class Main { 
    public static void main(String[] args) { 
     class Student{ 
      String fname; 
      String lname; 
      String mail; 
      int sum; 
      Student(String fn,String ln,String ml){ 
       fname=fn; 
       lname=ln; 
       mail=ml; 
       sum=0; 
      } 
      void addScore(int n){ 
       sum += n; 
      } 
      public String toString() { 
       return "Student: "+fname+" "+lname+", "+mail+" sum: "+sum; 
      } 
     } 
     try { 
      BufferedReader br = new BufferedReader(new FileReader(args[0])); 
      ArrayList<Student> stdnts = new ArrayList<Student>(); 
      String line = br.readLine(); 
      while (line != null) { 
       if (line.contains(";")) { 
        String[] stdnt_arr = line.split(";"); 
        Student stdnt = new Student(stdnt_arr[0],stdnt_arr[1],stdnt_arr[2]); 
        for (int i = 3;i<stdnt_arr.length;i++){ 
         try { 
          stdnt.addScore(Integer.parseInt(stdnt_arr[i])); 
         } catch (NumberFormatException e) { 
          //not a number 
          e.printStackTrace(); 
         } 
        } 
        stdnts.add(stdnt); 
        System.out.println(stdnt.toString()); 
       } 
       line = br.readLine(); 
      } 
     } catch(IOException e){ 
      //things went wrong reading the file 
      e.printStackTrace(); 
     } 
    } 
}