Interacting with the User

     

Interacting with the User

There are a few different ways to interact with the user from within an application. For desktop software, you use classes in the Swing packages javax.swing. There are servlets and JavaServer Pages that allow you to interact from a Web server. However, there are many occasions on which you just want something simpler. It can be difficult to set up Swing applications with sophisticated layouts, events, and handlers. There are many times too when a console application is not only fine, but is the best choice for interacting with the user. In these cases, you turn to the System class.

Reading User Input from the Console with System.in

When you want to print something out to the console, you use the print() or println() methods of the System.out object. To read user input from the console, get the static System.in object, which is of type InputStream. As with the OutputStream provided by the out object, this stream opens automatically when your program starts. So all you have to do is read from the stream. Sounds straightforward enough, right?

Well, not really.

We know that dealing with IO is often a little tricky, just because there are so many ways to do it. What type of field is InputStream? It is abstract, representing the superclass of all classes that accept data as byte arrays. That means that we need to wrap it in a class that defines a method for accepting bytes of input as characters . However, we're talking about a fairly costly operation: using a byte array reader to read data, then converting it to characters with an InputStream reader, returning the converted text constantly. What we need is a way to do all of that, but make a little temporary storage area, a buffer, for the character data. The most efficient way to do that is to wrap our InputStreamReader with a BufferedReader. So the call that gets data from System.in looks like this:

 

 BufferedReader in   = new BufferedReader(new InputStreamReader(System.in)) 

Now we have a reference that we can use to read each line of user input. To do that, we use a loop that checks for the end of the input, like this:

 

 while((line = in.readLine()) != null) { //strip spaces out just to show an operation happening line = line.replaceAll(" ", ""); } 

If you are going to do this sort of thing ( use runtime. exec () ),you really should read the next section after the Calculator code, called "Thread Issues with Runtime.exec()."

Note that if you want to compile the preceding code in a class, you will need to catch the exceptions thrown by the reader classes.



Java Garage
Java Garage
ISBN: 0321246233
EAN: 2147483647
Year: 2006
Pages: 228
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net