【问题标题】:why the while does not stop at the second loop为什么while不会在第二个循环处停止
【发布时间】:2018-06-19 08:30:43
【问题描述】:

在第一个循环中,while 停止并在 incomStr = view.read(); 处等待控制台输入,但在第二个循环中它不会停止,而是读取 null 并继续。

为什么会这样?

public void mainDialogueHolder() {//todo

        setCmdState(CmdLineState.WAIT);
        view.write("Hello, user!");
        view.write("Please, type `help` for list available commands. ");
        while (getCMDState().equals(CmdLineState.WAIT)){
            String incomStr;
            incomStr = view.read();//implementation is below
            readCmd(incomStr);
        }
    }

视图的实现

public class Console implements View {

    @Override
    public void write(String message) {
        System.out.println(message);
    }

    @Override
    public String read() {
        try (
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))
        ){
            return reader.readLine();
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
            return null;
        }
    }
}

【问题讨论】:

  • 如果它返回null,这意味着你通过了你的catch块。那么提示的消息是什么,应该说明错误是什么
  • 但是为什么它不停止并等待返回 reader.readLine();
  • 异常应该告诉你

标签: java while-loop readline


【解决方案1】:

看起来您尝试使用资源通过关闭 BufferedReader 来关闭 System.in,而后者又会关闭它的 Reader (InputStreamReader) 并关闭 System.in。 System.in 是最终静态的,因此一旦关闭它,您将无法再次使用它,因为无法重新打开它。 那么我该怎么办如果我不能关闭它? 也许你可以像这里建议的那样写一个包装器In Java is it possible to re-open System.in after closing it

【讨论】:

  • 是的。当我编写通常的 try-catch 时,它就可以工作了。谢谢大家
猜你喜欢
  • 1970-01-01
  • 2016-08-22
  • 2016-01-19
  • 1970-01-01
  • 1970-01-01
  • 2021-11-28
  • 2018-08-14
  • 1970-01-01
  • 2015-12-30
相关资源
最近更新 更多