Flush()打印两次

时间:2014-11-07 07:45:30

标签: java printwriter writer

我的代码打印了一条我不需要的额外新行。此外,如果我添加system.out.println(str),那么str打印两次,我不明白。

代码是

public void run() throws IOException
{
    boolean zeroEntered = false;
    int scenario = 1;

    //while a zero hasn't been entered
    while(!zeroEntered)
    {
        boolean stop = false;
        String input;
        int numTeams = rdr.nextInt();
        Teams teams = new Teams(numTeams);

        //if there are 0 teams, then stop
        //and set zeroEntered to true
        if(numTeams == 0)
        {
            stop = true;
            zeroEntered = true;
        }
        else
        {
            //else write the scenario number
            wtr.write("Scenario #" + scenario + "\n");
            wtr.flush();
            scenario++;
        }

        //for the number of teams entered index
        for(int index = 0; index < numTeams; index++)
        {
            int numPlayers = rdr.nextInt();

            //add the number pNum of players
            for(int pNum = 0; pNum < numPlayers; pNum++)
            {
                //adds the player scanned
                int player = rdr.nextInt();
                teams.addPlayer(player, index);
            }
        }

        AthleteQueue lunchLine = new AthleteQueue(teams);

        //while there is still entry, and stop hasn't been entered
        while(rdr.hasNextLine() && !stop)
        {
            input = rdr.next();
            //if enter , then enqueue the next read player
            if(input.equals("ENTER"))
            {
                lunchLine.enqueue(rdr.nextInt());
            }
            //else serve, enqueue and print
            else if(input.equals("SERVE"))
            {
                wtr.write(lunchLine.dequeue() + "\n");
                wtr.flush();
            }
            //stop if there is no entry
            else
            {
                stop = true;
            }
        }

        //two lines after? why?
        wtr.write("\n");
    }

    wtr.flush();
    System.out.println("WHY");
}

此方法位于具有Scanner rdr和Writer wtr实例变量的类中。在这种情况下,传入了bufferedReader和printWriter。起始代码有点无关紧要。我只是把它包括在内以防错误可能存在。在最后几行中,打印了一条额外的新行,并打印了额外的原因。我相信这是因为冲洗方法。有人可以解释为什么会发生这种情况以及如何解决这个问题。我很感激帮助。

1 个答案:

答案 0 :(得分:0)

我猜是因为你提到了&#39; \ n&#39;在循环内的wtr.write(lunchLine.dequeue() + "\n");中以及在再次退出循环后,您正在编写一个新行wtr.write("\n");,这将导致两个新行 - 一个来自循环内部的最后一次迭代,另一行from wtr.write("\n")