如何在Java中正确使用拆分

时间:2013-01-11 19:29:01

标签: 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  

我对如何获取这些数据集并将它们放入2D数组感到困惑,这样我就可以询问用户是否要排序,搜索玩家,添加它们等等。

如果有人能帮助我,请多谢!

4 个答案:

答案 0 :(得分: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);
        }

享受......

答案 1 :(得分:0)

这是我遇到的问题。

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

您的尺寸似乎在此处向后移动,稍后您将其称为:

hockeyStats[x][y]

您在x中迭代超过30个玩家,在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];
    }
}

答案 2 :(得分: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();
    

    }

答案 3 :(得分: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");
    }
}

我总是觉得通过引入一些结构,你的程序会变得多么美妙。