是否有与 getchar 等效的 Java?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4831861/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a Java equivalent to getchar?
提问by Adrian
I have a simple client server program, wherein I have a problem with my menu:
我有一个简单的客户端服务器程序,其中我的菜单有问题:
do {
System.out.println("---- MENU ----\n");
System.out.println("(drv) - List drives");
System.out.println("(pwd) - Current path");
System.out.println("(ls) - List files in a directory");
System.out.println("(quit) - Quit program\n");
System.out.print("Enter a command: ");
command = scanner.nextLine();
sendMessage(command);
message = (String)in.readObject();
System.out.println(message);
System.in.read();
}while(!command.equals("quit"));`
I want to print the result on the screen, wait until I press Enterand then show the menu again, so I use System.in.read()
. My problem is that it works the first time, but if I choose another option it doesn't print anything:
我想在屏幕上打印结果,等到我按下Enter然后再次显示菜单,所以我使用System.in.read()
. 我的问题是它第一次工作,但如果我选择另一个选项,它不会打印任何内容:
---- MENU ----
(drv) - List drives
(pwd) - Current path
(ls) - List files in a directory
(quit) - Quit programEnter a command: pwd
D:\Documents and Settings\asname\workspace_java\server---- MENU ----
(drv) - List drives
(pwd) - Current path
(ls) - List files in a directory
(quit) - Quit programEnter a command: ls
- - 菜单 - -
(drv) - 列出驱动器
(pwd) - 当前路径
(ls) - 列出目录中的文件
(quit) - 退出程序输入命令:pwd
D:\Documents and Settings\asname\workspace_java\server- - 菜单 - -
(drv) - 列出驱动器
(pwd) - 当前路径
(ls) - 列出目录中的文件
(quit) - 退出程序输入命令:ls
Is there a method in Java similar to getchar
that I could use instead?
Java 中是否有类似于getchar
我可以使用的方法?
采纳答案by Adrian
Just add scanner.nextLine();
after System.out.println(message);
so it waits
只需在scanner.nextLine();
之后添加即可 System.out.println(message);
等待