2014-09-27 35 views
0

我正在嘗試讀取文件並以特定格式打印出結果。打印時,它只打印每一個其他條目。在while循環中,我嘗試切換if語句並將0更改爲-1,然後對++進行計數,但無效。從java中讀取文件,但輸出會跳過其他所有行

try 
    { 
    File f = new File("BaseballNames1.csv"); 
    FileReader fr = new FileReader(f); 
    BufferedReader br = new BufferedReader(fr); 

    ArrayList<String> players = new ArrayList<String>(); 
    String line; 
    int count = 0; 

    while((line = br.readLine()) != null) 
    { 
     if(count == 0) 
     { 
      count++; 
      continue; 
     } 
     players.add(br.readLine()); 
    } 

    for(String p : players) 
    { 
     String[] player = new String[7]; 
     player = p.split(","); 

     first = player[0].trim(); 
     last = player[1].trim(); 
     birthDay = Integer.parseInt(player[2].trim()); 
     birthMonth = Integer.parseInt(player[3].trim()); 
     birthYear = Integer.parseInt(player[4].trim()); 
     weight = Integer.parseInt(player[5].trim()); 
     height = Double.parseDouble(player[6].trim()); 
     name = first + " " + last; 
     birthday = birthMonth + "/" + birthDay + "/" + birthYear; 
     System.out.println(name + "\t" + birthday + "\t" + weight + "\t" + height); 
     //System.out.printf("First & Last Name %3s Birthdate %3s Weight %3s Height\n", name, birthday, weight, height); 
    } 
    } 
    catch(Exception e) 
    { 
    e.getMessage(); 
    } 
+0

在添加剛剛閱讀的行之前,您要調用br.readLine()兩次。所以它應該是players.add(線); – Juniar 2014-09-27 15:50:14

回答

2

我覺得你的問題就在這裏:

while((line = br.readLine()) != null) 
{ 
    if(count == 0) 
    { 
     count++; 
     continue; 
    } 
    players.add(br.readLine()); 
} 

你正在閱讀一個新行每一次,即使您已經閱讀之一。你想這樣的:

while((line = br.readLine()) != null) 
{ 
    if(count == 0) 
    { 
     count++; 
     continue; 
    } 
    players.add(line); //The important change is here. 
} 
+0

啊啊謝謝@ Pokechu22! – 2014-09-27 17:16:21

1

變化

players.add(br.readLine()); 

players.add(line); 

您的版本讀取和寫入下一行players,不是當前。

相關問題