2014-05-02 31 views
0

文本文件:處理從文本文件中的字符串,並繼續與Java程序

9310,12,120,2,1 
9333,12,120,2,1 
PRINT 
9533,5,45,0,0 
8573,10,120,1,0 
6343,6,18,170,0 
PRINT 
9311,12,120,2,1 
3343,7,20,220,0 

代碼

import java.io.BufferedReader; 
import java.io.DataInputStream; 
import java.io.FileInputStream; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.util.ArrayList; 
import java.util.Collections; 
i mport java.util.Comparator; 
import java.util.List; 


public class FantasyPlayers { 

    int player_ID; 
    int total_score; 

    public FantasyPlayers(int player, int total) { 
     player_ID = player; 
     total_score = total; 
    } 

    public String toString() { 
     return player_ID + "," + total_score; 
    } 

    /** 
    * @param args 
    * @throws IOException 
    */ 
    public static void main(String[] args) throws IOException { 
     FileInputStream fstream = new FileInputStream("Stats.txt"); 
     DataInputStream in = new DataInputStream(fstream); 
     BufferedReader br = new BufferedReader(new InputStreamReader(in)); 

     String delims = "[,]"; 
     List<FantasyPlayers> Stats = new ArrayList<FantasyPlayers>(); 
     int a = 2; 
     int b = 1; 
     int c = 6; 
     int d = -1; 
     for (String line; (line = br.readLine()) != null;) 
     { 
      String[] parsedData = line.split(delims); 
      if (line != "PRINT") 
      { 
      int score = Integer.parseInt(parsedData[1])*a + Integer.parseInt(parsedData[2])*b + Integer.parseInt(parsedData[3])*c + Integer.parseInt(parsedData[4])*d ; 
      Stats.add(new FantasyPlayers(Integer.parseInt(parsedData[0]), score)); 
      } 
      else 
       continue; 
     } 
     br.close(); 

     System.out.println("Unordered"); 
     for (FantasyPlayers str : Stats) 
     { 
       System.out.println(str); 
     } 
     Collections.sort(Stats, new Comparator<FantasyPlayers>() 
      { 
      public int compare(FantasyPlayers one, FantasyPlayers two) 
      { 
       if (one.total_score == two.total_score){ 
        Integer playerOne = one.player_ID; 
        Integer playerTwo = two.player_ID; 

        return playerTwo.compareTo(playerOne); 
       } 
       Integer scoreOne = one.total_score; 
        Integer scoreTwo = two.total_score; 

       return scoreTwo.compareTo(scoreOne); 
       } 
     }); 
     System.out.println("Ordered"); 
     for (FantasyPlayers str : Stats) 
     { 
      System.out.println(str); 
     } 

    } 

} 

我不斷收到錯誤ArrayIndexOutOfBoundsException異常:1在int score =位置。

我的問題是我如何處理代碼中的PRINT語句......我能夠對數據做我想做的事情,但我需要邏輯在讀取print語句時執行某些操作。有什麼建議麼?

回答

3

你,我的朋友已經愛上了最常見的Java錯誤....

試試這個

if (!line.equalsIgnoreCase("PRINT")) 
+0

這個作品!......多謝 – koala421

2

試圖改變這一行

String delims = "[,]"; 

String delims = ","; 

這行

line != "PRINT" 

!line.trim().equals("PRINT") 
相關問題