1

我一直在做这个代码,但我一直坚持如何正确拆分文本文件。我怎么能做到这一点?我正在使用二维数组,同时从文本文件中读取。

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();

我必须做什么?我不明白这里的问题。这是我的文本文件中的内容,Vancouver Stats

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  

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

如果有人可以帮助我,请感谢!

4

4 回答 4

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);
        }

享受......

于 2013-01-11T20:41:21.100 回答
0

我正在为您的问题提供工作代码。代码如下。我将尝试解释您实施错误的一些事情。

  1. hockeyStats[x][y]=temp[y];由于前进超过 8,因此超出界限异常x。记住hockeyStats大小为 8x30
  2. String temp[]=listnumbers.split(" ")命中空异常,因为listnumbers=input.readLine();可能没有读取任何输入。这发生在文件的末尾。

    导入 java.io.BufferedReader;导入 java.io.FileReader;导入 java.io.FileNotFoundException;导入 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();
    

    }

于 2013-01-11T20:04:25.293 回答
0

这是我遇到的问题。

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

考虑到稍后您指的是:

hockeyStats[x][y]

在其中迭代 30 多个玩家x,以及 8 个属性y。您应该声明您的 stats 数组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];
    }
}
于 2013-01-11T19:39:59.460 回答
0

为了可维护性,我们可以做的简化事情是为您的 stat 持有者创建一个有用的类结构类。

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().

您必须添加自己的方法来按特定参数(例如名称或某些统计信息)进行搜索,但是现在组装数组要容易得多。

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");
    }
}

我总是发现通过引入一些结构可以使您的程序变得更好,这真是令人惊讶。

于 2013-01-11T23:19:31.043 回答