• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to input something ?

 
E Lan
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
E Lan
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can read bytes one at a time from InputStream.

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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic