Java Reference
In-Depth Information
Self-Test Exercises
10. Write an import statement that makes the Scanner class available to your pro-
gram or other class.
11. Write a line of code that creates a Scanner object named frank to be used for
obtaining keyboard input.
12. Write a line of code that uses the object frank from the previous exercise to read
in a word from the keyboard and store the word in the String variable named w .
13. Write a complete Java program that reads in a line of keyboard input containing
two values of type int (separated by one or more spaces) and outputs the two
numbers as well as the sum of the two numbers.
14. Write a complete Java program that reads in a line of text containing exactly three
words (separated by any kind or amount of whitespace) and outputs the line with
spacing corrected; that is, the output has no space before the first word and
exactly one space between each pair of adjacent words.
EXAMPLE: Self-Service Check Out
Display 2.9 contains a first draft of a program to use in the self-service line of a hardware
store. It still needs some more details and even some more hardware for accepting pay-
ment. However, it does illustrate the use of the Scanner class for keyboard input and the
printf method for formatted output.
Note that in printf , we used the format specifier %.2f for amounts of money. This
specifies a floating-point number with exactly two digits after the decimal point, but
gives no field width. Because no field width is given, the number output is placed in the
fewest number of spaces that still allows the full value to be shown.
Other Input Delimiters
When using the Scanner class for keyboard input, you can change the delimiters that sep-
arate keyboard input to almost any combination of characters, but the details are a bit
involved. In this topic, we will describe only one simple kind of delimiter change. We will
tell you how to change the delimiters from whitespace to one specific delimiter string.
Search WWH ::




Custom Search