2013-01-11 29 views
1

我一直在做這個代碼,但我一直在堅持如何正確拆分文本文件。我將如何能夠做到這一點?我正在使用一個二維數組,同時從文本文件中讀取數據。如何在Java中正確使用拆分

Scanner sc= new Scanner (System.in); 
    int entry; 
    String hockeyStats[][] = new String[8][30];//Array initialized, up to 30 players in total can be in the database. 
    BufferedReader input = new BufferedReader (new FileReader ("Vancouver Stats.txt"));//Text file with player names imported. 
    // FULL NAME, GOALS, ASSISTS, PLUSMINUS, PENALTY MINUTES, SHOTS 
    String listnumbers="word"; 
    while (listnumbers!=null) 
    { 
     for (int x=0; x<30;++x) 
     { 
      listnumbers=input.readLine(); 
      String temp[]=listnumbers.split(" "); 
      for (int y=0; y<7;++y) 
      { 
       hockeyStats[x][y]=temp[y]; 
      } 

     } 
    } 
    input.close(); 

我該做什麼?我不明白這裏的問題。這裏是什麼,是我的文本文件,溫哥華統計裏面

Kesler Ryan 22 27 11 56 222 
Sedin Henrik 14 67 23 52 113 
Edler Alexander 11 38 0 34 228 
Hansen Jannik 16 23 18 34 137 
Hamhuis Dan 4 33 29 46 140 
Tanev Christopher 0 2 10 2 15 

我很困惑於如何得到這些數據集,並把它們放入一個二維數組,這樣我就可以詢問用戶是否要進行排序,搜索玩家,添加他們等等。

如果有人能幫助我,請致謝!

+2

實際上,將數據放入表示您向後插入數據的播放器 – informatik01

+0

的_Array_對象會更好也更合乎邏輯。你的數組是8行,30列,但是當你迭代它並插入你的行列時。您的尺寸不匹配,您的程序將崩潰。這就是爲什麼我們使用諸如yourArray.length和yourArray [0] .length之類的東西來代替迭代循環的硬編碼值。 – nhydock

回答

0

這是我遇到的問題。

String hockeyStats[][] = new String[8][30]; 

你似乎有你的尺寸落後這裏,後來考慮到你指的是:

hockeyStats[x][y] 

如果您遍歷30名球員在x,並在y 8個屬性。你應該聲明你的統計數組new String[30][8]。如果問題是ArrayIndexOutOfBoundsException,那就應該解決它。


String listnumbers="word"; 
//Here, we check for a null value. Two reasons this isn't working, see the following comments. 
while (listnumbers!=null) 
{ 
    //Looping through 30 records, without ever touching the while loop. 
    //This attempts to read and add 30 lines, then checks whether listnumbers is null 
    //(and if not, adds another 30, etc.) 
    for (int x=0; x<30;++x) 
    { 
     //You might get listnumbers == null here 
     listnumbers=input.readLine(); 
     //And if you do, it will throw an exception here! 
     //Note, there is nothing checking for null between those two points. 
     String temp[]=listnumbers.split(" "); 
     for (int y=0; y<7;++y) 
     { 
      hockeyStats[x][y]=temp[y]; 
     } 

    } 
} 

有一對夫婦,你可以使用替代品。一個是,擺脫while循環,而不是這樣做:

for (int x=0; x<30;++x) 
{ 
    listnumbers=input.readLine(); 
    if (listnumbers == null) break; 
    String temp[]=listnumbers.split(" "); 
    for (int y=0; y<7;++y) 
    { 
     hockeyStats[x][y]=temp[y]; 
    } 
} 
+0

我以爲它是基於行和列? ARRAY [行] [列]?我有這樣的設置,但現在它給了我一個錯誤 String temp [] = listnumbers.split(「」); 爲空? –

+0

您可以將其視爲行和列,但在這種情況下,您聲明它具有[rows = 8] [columns = 30],它仍然向後。 – femtoRgon

+0

好吧,當然可以。你在迭代列表時遇到了一些問題,現在我正在更仔細地查看它。我會更新我的回答,並附上一些評論。 – femtoRgon

0

我正在爲您的問題提供一個工作代碼。代碼如下。我會試着解釋一些你實施錯誤的東西。

  1. hockeyStats[x][y]=temp[y];獲取綁定異常的出局,因爲x前進經過8記住hockeyStats是大小的8x30
  2. String temp[]=listnumbers.split(" ")命中空例外,因爲listnumbers=input.readLine();可能無法讀取任何輸入。這發生在文件的末尾。

    import java.io.BufferedReader; import java.io.FileReader; import java.io.FileNotFoundException; import java.io.IOException;

    public class vvvd { 
    
    public static void main(String[] ards) throws FileNotFoundException, IOException{ 
    //Scanner sc= new Scanner (System.in); 
    int entry; 
    String hockeyStats[][] = new String[8][30];//Array initialized, up to 30 players in total can be in the database. 
    BufferedReader input = new BufferedReader (new FileReader ("Vancouver.txt"));//Text file with player names imported. 
    // FULL NAME, GOALS, ASSISTS, PLUSMINUS, PENALTY MINUTES, SHOTS 
    String listnumbers="word"; 
    
    listnumbers=input.readLine(); 
    int x = 0; 
    while (listnumbers!=null) 
    { 
        //for (int x=0; x<8;++x) 
        //{ 
    
         if(x >= 8) 
          break; 
    
         String temp[]=listnumbers.split(" "); 
         for (int y=0; y<7;++y) 
         { 
          hockeyStats[x][y]=temp[y]; 
         } 
    
        //} 
        x++; 
    listnumbers=input.readLine(); 
    } 
    input.close(); 
    

    }

+0

如果temp在hockeyStats [x] [y] = temp [y]中的長度小於8,該怎麼辦;?錯誤,出界, –

1

你可以閱讀你的測試文件和管理使用下面的代碼段數據。

try { 
      File file=new File("asd.txt"); 
      Scanner sc=new Scanner(file); 
      /* 
      * If Players name are unique 
      */ 
      Map<String,ArrayList> mPlayerData=new HashMap(); 
      ArrayList mData=new ArrayList(); 

      while(sc.hasNext()){ 
       String mPlayerName=""; 
       Scanner sc2=new Scanner(sc.nextLine()); 
       sc2.useDelimiter(" "); 
       int i=0; 
       while(sc2.hasNext()){ 
        if(i<2){ 
         mPlayerName=mPlayerName.equalsIgnoreCase("")?sc2.next():mPlayerName+" "+sc2.next(); 
        }else{ 
         mData.add(sc2.next()); 
        } 
        i++; 
       } 
       mPlayerData.put(mPlayerName, mData); 
      } 
      System.err.println(mPlayerData.size()); 
     } catch (FileNotFoundException ex) { 
      Logger.getLogger(JavaApplication1.class.getName()).log(Level.SEVERE, null, ex); 
     } 

享受......

0

可維護性的緣故,我們可以做什麼來簡化事情是爲您的統計持有者一個有用的結構類類。

static class HockeyPlayer extends Comparable<HockeyPlayer> 
{ 
    static final int VALUES_LENGTH = 5; //we like knowing how many stats we should be handling 
    String lastName; 
    String firstName; 
    int[] values; 

    /** 
    * Creates a data structure holding player data of hockey stats 
    * @throws FormatException 
    *  when the data passed in does not have enough values stored or if 
    *  the stats could not be parsed into integers 
    */ 
    public HockeyPlayer(String data) throws FormatException 
    { 
     String[] parsedData = data.split(); 
     if (data.length != 2 + VALUES_LENGTH) 
     { 
      throw new FormatException(); 
     } 
     lastName = parsedData[0]; 
     firstName = parsedData[1]; 
     values = new int[VALUES_LENGTH] 
     // we use two counters, one for the parsed data index and 
     // another for the values index 
     for (int i = 0, j = 2; i < values.length; i++, j++) 
     { 
      //make sure the numbers are parsed into int 
      values[i] = Integer.parseInt(parsedData[j]); 
     } 
    } 

    /** 
    * Comparison handling method of Comparable objects. 
    * Very useful in sorting 
    * @return 0 when equal, -1 when less than, 1 when greater than 
    */ 
    public int compareTo(HockeyPlayer player2) 
    { 
     //I'll leave this for you to set up since you know how you want your values organized 
     return 0; 
    } 
} 

這樣格式化的類可能會有很大的幫助,原因很多。首先,如果某行的格式不正確,而不是破壞程序,則可能比執行大量if語句更容易發現錯誤,因爲它會給您一個例外,明確指出該行格式錯誤。最重要的是,它實現了Comparable類,其數據類型爲HockeyPlayer,它可以與之比較。如果您將數據存入ArrayList<HockeyPlayer>,您可以輕鬆添加新玩家,並可以使用Collections.sort()進行排序。

你必須添加自己的方法來搜索特定的參數,比如名字或stat,但是現在組裝這個數組變得更容易了。

ArrayList<HockeyPlayer> list = new ArrayList<HockeyPlayer>(); 

while (input.hasNextLine()) 
{ 
    String data = input.nextLine(); 
    try 
    { 
     HockeyPlayer player = new HockeyPlayer(data); 
     list.add(player); 
    } 
    catch (FormatException e) 
    { 
     System.err.println("Player data not formatted correctly"); 
    } 
} 

我總是發現它真的很棒,你的程序可以通過引入幾個結構體而變得更好。

+0

哇,我從來沒有見過這個。你用ArrayList添加的這些結構是什麼? –

+0

@Bobby很抱歉,真的很晚迴應。 ArrayLists允許您將類型分配用於可由其管理的各種內容。你可以將它實現到你創建的任何類中。他們被稱爲泛型,或偶爾會看到他們稱爲模板 – nhydock