This is a easy question. For example: We write a program that is about one game.In this program,there is a request that when user end this game one time,computer must ask user :"Want to play one more time?(y\n)". And if user input 'y',then the game will restart,if user input other words,then this program finished. But I don't know how to get the user's input. Like above example,how to get the input 'y' or 'n' or other words from user? What command I must use? What shold I do? To clearly,if we write program in C++,we can use the command "cin>>"to get user's input.Is there any command like "cin>>" in language java?
Thanks you to answer my immature question. [ June 10, 2004: Message edited by: E Lan ]
Just as you use System.out to write to the console, you can use System.in to read. Looking at the JavaDoc System.in is of type InputStream, and that lets you read individual bytes or arrays of bytes. Not very friendly.
Something like BufferedReader would be nice because it has readLine(). So let's look at the constructor docs for BufferedReader. Takes a Reader, and InputStream is not a Reader, so we can't hook that up directly. Follow the link to Reader and see what implements Reader. Hey, InputStreamReader sounds promising. Follow that link and sure enough it has an InputStream constructor.
So here's the finished product:
You'll often see this shortcut ...
The only bad news is that the Java console does not support reading individual keystrokes. So the user has to hit "Y+Enter" instead of just "Y". We all just have to live with that.
Hope that helps! Actually, hope it works. I'm typing without testing.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Joined: Mar 15, 2004
Thank you very much~Stan James,what you teach me is helpful. I have written a simple program to test,and that did work!
Additionally, after read your article,I am interested in how to use "System.in" to get inputs ,even it just can get bytes input data. Could you leak some information for me? Thanks again [ June 10, 2004: Message edited by: E Lan ]
This will read characters until the user hits Ctrl-Z for EOF. On Windows anyhow. You can adjust the loop to read up to a new line '\n' or some special character or whatever you like. Experiment with it and see how it responds to normal characters, ctrl and alt and other odd keystrokes.