简体   繁体   English

Java中的“ System.in.read()”

[英]“System.in.read()” in Java

I have a problem with this method: 我对此方法有疑问:

public void runTransaction(){
   //Some calculations...
   wait();
   //Other calculations...
}

private static void wait(){
   try {
        System.out.println("Press <enter> to continue");
        System.in.read();
    } 
    catch (java.io.IOException ex) {
        System.out.println("Input error...");
    }
}

but the programm does not continue after pressing Enter. 但是按Enter键后程序不会继续。 I'm using Ubuntu 12.04. 我正在使用Ubuntu 12.04。

EDIT: the programm does print the message "Press to continue" but does not continue after that, it just waits for input. 编辑:该程序不会打印消息“按继续”,但此后不继续,它只是在等待输入。

This shouldn't even compile: 这甚至不应该编译:

  1. in.read() can throw an IOException , which you need to handle. in.read()可能引发IOException ,您需要处理它。 ( EDIT: Looks like you fixed this issue in your snippet.) 编辑:看起来您已在代码段中解决了此问题。)

  2. You can't name this method wait() since that hides Object 's wait() . 您无法将此方法命名为wait()因为它隐藏了Objectwait()

Once these errors are corrected, the code should work as expected. 纠正这些错误后,代码应会按预期工作。

Does your code even compile? 您的代码是否可以编译? The wait method is public on the Object class, thus it can not be overridden as private. wait方法在Object类上是公共的,因此不能将其重写为private。 Try using a different method name, say waitForInput . 尝试使用其他方法名称,例如waitForInput

如果您将名称更改为wait_enter,您的代码应按预期运行,您只需要确保在按Enter键之前单击控制台即可注册Enter键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM