Java Reference
In-Depth Information
Self-Test Exercises
10. Write an import statement that makes the Scanner class available to your
program 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 fi rst
word and exactly one space between each pair of adjacent words.
15.
Something could go wrong with the following code. Identify and fi x the
problem.
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your age.");
int age = keyboard.nextInt();
System.out.println("Enter your name.");
String name = keyboard.nextLine();
System.out.println(name + ",you are " + age + " years old.");
EXAMPLE: Self-Service Checkout
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 payment. 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.
 
Search WWH ::




Custom Search