Page 127 - Introduction to Programming with Java: A Problem Solving Approach
P. 127
2. What happens if the user provides invalid input?
The JVM prints an error message and stops the program. For example, if a user enters 45g or 45.0 in response to a nextInt() call, the JVM prints an error message and stops the program.
3. The next method looks for a token. What is a token?
Think of a token as a word since the next method is usually used for reading in a single word. But more formally, a token is a sequence of non-whitespace characters. For example, “gecko” and “B@a!” are tokens. But “Gila monster” is not a token because of the space between “Gila” and “monster.”
Examples
To make sure you understand Scanner methods, study the programs in Figures 3.14 and 3.15. They illus- trate how to use the nextDouble, nextInt, and next methods. Pay particular attention to the sample sessions. The sample sessions show what happens when the programs run with typical sets of input. In
3.23 Input—the Scanner Class 93
/**************************************************************
*
PrintPO.java
Dean & Dean
This program calculates and prints a purchase order amount.
**************************************************************/
*
*
*
import java.util.Scanner;
Apago PDF Enhancer
public class PrintPO
{
}
// end class PrintPO
public static void main(String[] args)
{
}
System.out.print("Price of purchase item: ");
price = stdIn.nextDouble();
System.out.print("Quantity: ");
qty = stdIn.nextInt();
System.out.println("Total purchase order = $" + price * qty);
// end main
Scanner stdIn = new Scanner(System.in);
double price; // price of purchase item
int qty;
// number of items purchased
Sample session:
Price of purchase item: 34.14
Quantity: 2
Total purchase order = $68.28
Figure 3.14 PrintPO program that illustrates nextDouble() and nextInt()