A.4. Interacting with the User

Accepting arguments from the command line is helpful, but our programs would be very limited if we had no other way to interact with the user. We also need to be able to print text to the screen and read input from the keyboard.

Printing text is accomplished with the System.out.println() method, as used previously. There is a related method System.out.print(), which does not move on to the next line.

Before Java 1.5, reading from the keyboard was fantastically awkward. The introduction of the new Scanner class makes it reasonable. Before reading from the keyboard, a program must create a Scanner with the following incantation:

java.util.Scanner input = new java.util.Scanner(System.in);

This may seem somewhat cryptic at this point, but we have seen this kind of statement already. This is a declaration and initialization of a variable input. The type of the variable is java.util.Scanner, which will make more sense after we discuss packages (Section 3.3). The part to the right of the equals sign gives input its initial value. Specifically, it is the invocation of a constructor (Section 1.2). It doesn't matter that we don't understand these things just yet.

Now that we have input, we can read from the keyboard. If we store the next line typed by the user in a variable answer, we do this:

String answer = input.nextLine();

We can also ask for input.nextInt() to get an int from the user, input.nextDouble() to get the next double, and so on. A technical detail is that these methods only "use up" the number in question, not the entire line of input. If we want to go on to ask the user for non-numeric input, we should invoke nextLine() to clear out the rest of the line. In a program that only asks for numbers, this can be ignored. We will do more elaborate things with the Scanner class over the course of the book.

Exercises

A.11

Modify the Hello program in Figure A-2 so that it asks the user for her name and then greets her by name.


Part I: Object-Oriented Programming

Encapsulation

Polymorphism

Inheritance

Part II: Linear Structures

Stacks and Queues

Array-Based Structures

Linked Structures

Part III: Algorithms

Analysis of Algorithms

Searching and Sorting

Recursion

Part IV: Trees and Sets

Trees

Sets

Part V: Advanced Topics

Advanced Linear Structures

Strings

Advanced Trees

Graphs

Memory Management

Out to the Disk

Part VI: Appendices

A. Review of Java

B. Unified Modeling Language

C. Summation Formulae

D. Further Reading

Index



Data Structures and Algorithms in Java
Data Structures and Algorithms in Java
ISBN: 0131469142
EAN: 2147483647
Year: 2004
Pages: 216
Authors: Peter Drake

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