【问题标题】:Java - output from line read in reverseJava - 反向读取的行输出
【发布时间】:2012-06-14 19:18:09
【问题描述】:

以下例程输出从国际象棋引擎转移到 JTextArea

public void getEngineOutputOriginal(Process engine) 
{
    try {           
        BufferedReader reader =
          new BufferedReader (new InputStreamReader (engine.getInputStream ()), 1);
        String lineRead = null;
        // send engine analysis to print method
        while ((lineRead = reader.readLine ()) != null)
           Application.showEngineAnalysis (lineRead);
    }
    catch (Exception e) {
                      e.printStackTrace();
    }
}

示例输出将是

           12     3.49  39/40?  2. b4      (656Knps)             
           12     3.49  40/40?  2. Nd5     (656Knps)             
           12->   3.51   0.04   2. Bxf4 Be6 3. Be3 Qa5 4. Nd5 Qxd2
           13     3.51   1/40?  2. Bxf4    (655Knps)   

是否可以颠倒这个过程,使最后一行读取的始终出现在顶部而不是底部,如下所示:

           13     3.51   1/40?  2. Bxf4    (655Knps)   
           12->   3.51   0.04   2. Bxf4 Be6 3. Be3 Qa5 4. Nd5 Qxd2
           12     3.49  40/40?  2. Nd5     (656Knps)             
           12     3.49  39/40?  2. b4      (656Knps)     

我研究了 Google,但找不到解决方案

【问题讨论】:

    标签: java line reverse


    【解决方案1】:

    当然!一种选择是将这些行缓冲到ArrayList,然后在最后以相反的顺序显示它们:

    List<String> lines = new ArrayList<String>();
    
    /* Add all lines from the file to the buffer. */
    while((lineRead = reader.readLine()) != null) {
        lines.add(lineRead);
    }
    
    /* Replay them in reverse order. */
    for (int i = lines.size() - 1; i >= 0; i--) {
         Application.showEngineAnalysis(lines.get(i));
    }
    

    从概念上讲,您可以将其视为创建一个堆栈,将所有行压入堆栈,然后一次将它们弹出一个。

    希望这会有所帮助!

    【讨论】:

    • 听起来不错 - 感谢您的快速响应。我试试看。
    • 代码效果很好,但是当我停止例程运行时,我只看到反向分析,即它在运行时不会刷新,等等。有什么想法吗?谢谢
    • @user1432365- 哦,我明白你在说什么。当您运行上述程序时,我认为该过程已经完成。您可能需要查看记录器以了解有关如何反转输出的详细信息。
    • 你说的logger是指我的输出方式,即: public static void showEngineAnalysis (String message) { if (message.length() > 0) message += "\n"; Application.obj.engineOutput.append(message); }
    • @user1432365- 是的,您需要更新该方法以显示在顶部而不是底部。我不知道 Application.obj.engineOutput 是什么,但你应该只是在消息前面而不是附加它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-13
    • 2011-12-30
    • 2015-04-17
    • 2023-02-04
    • 1970-01-01
    • 1970-01-01
    • 2015-03-08
    相关资源
    最近更新 更多