从文件中打印出正确的数据

时间:2015-08-11 04:16:31

标签: java file-io printing

如何打印正确的数据,因为无论何时打印,它都会打印出最后一个人的数据。例如,文件中有2个数据,如下所示。我希望我的输出像输出2,但我一直得到输出1.

输入

Bob Joe

23

Alie May

34

输出1:

Alie May 34

Alie May 34

输出2:

Bob Joe 23

Alie May 34

 private Player players = new Player();
 private List<Player> player = new ArrayList<Player>();

public void Read() throws IOException
{

    BufferedReader bs = new BufferedReader(new FileReader("Player.txt"));


    while((line1 = bs.readLine()) != null)
    {
        String[] token = line1.split(" ");
        players.setfName(token[0]);
        players.setlName(token[1]);
        players.setScore(Integer.parseInt(bs.readLine()));

        player.add(players);
    }

    bs.close();
}

public void print()
{
    for(Player p : player)
    {   
        System.out.println(players.getfName() + " " + players.getlName() + " " + players.getScore());
    }
}

3 个答案:

答案 0 :(得分:0)

问题出在while循环中。您正在将相同的对象players添加到列表中。您需要为列表中的每个条目创建一个新对象。

答案 1 :(得分:0)

变量playerswhile loop共享,该列表具有相同的对象players

您应该按照以下方式执行

while((line1 = bs.readLine()) != null)
{   
    Player players1 = new Player();
    String[] token = line1.split(" ");
    players1.setfName(token[0]);
    players1.setlName(token[1]);
    players1.setScore(Integer.parseInt(bs.readLine()));

    player.add(players1);
}

同时,这里有一个错误

 System.out.println(players.getfName() + " " + players.getlName() + " " + players.getScore());

您应该将players更改为p

希望有所帮助

答案 2 :(得分:0)

 System.out.println(players.getfName() + " " + players.getlName() + " " + players.getScore());

因为您正在打印players,其中包含您最后输入的玩家信息。

更新行如下:

System.out.println(p.getfName() + " " + p.getlName() + " " + p.getScore());