是否有与 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 08:14:28  来源:igfitidea点击:

Is there a Java equivalent to getchar?

java

提问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 program

Enter 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 program

Enter 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 getcharthat 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);等待