Go through this Java™ Tutorials section. In many cases, the easiest way to do that is to use System.in and a Scanner object. The API documentation for Scanner gives a simple example.
Beware: with Scanner it is occasionally necessary to discard a line.
would store console input in a String variable (until your user presses Enter).
The fine print: This method reads a line from standard input, which is not always (but usually) the same as "from console". It returns an empty String and not null for reasons I do not want to confess (hint: laziness is a powerful force). And using a BufferedReader in this method is a bit like using cannons to shoot down sparrows, but it was also a bit of a training example for me. The exception handling should have been more exact but it works for me...
Campbell Ritchie wrote:That method is incomplete because you are not closing the Reader in a finally block.
Ah, this encourages me to a question that - being a newbie - I haven't solved myself yet:
When I use this:
I get a compiler error, because "input.close()" throws an exception which must be handled. How can I guarantee the freedom of the used system resources? One way would be to add another try-catch-clause:
That would compile but if an error during closing happens there is no way to free the resources. Is there any method I overlooked which simply deallocates the resources bound and does nothing else? Or is "close()" *it* and an error could only occur during a major earthquake or large sun flares?
A nested try/catch is the appropriate answer, although I might refactor it out. If it's a long-running program why not just keep it open and not create a new reader every time you want to read something?
Agree with David N that you might do well to keep the Reader open. This is how you can nest try blocksObviously you can do different things with the input from simply returning one line. You would also omit the catch (FileNotFoundException) block if reading from System.in, because System.in doesn't use any Files.
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop