Page 128 - Introduction to Programming with Java: A Problem Solving Approach
P. 128
94 Chapter 3 Java Basics
Figure 3.14, note the italics for 34.14 and 2. In Figure 3.15, note the italics for Malallai
italicize input values in order to distinguish them from the rest of the program. Be aware that the italiciza- tion is a pedagogical technique that we use for clarification purposes in the book. Input values are not really italicized when they appear on a computer screen.
Zalmai. We
/*******************************************************************
*
PrintInitials.java
Dean & Dean
This program prints the initials for a user-entered name.
*******************************************************************/
*
*
*
import java.util.Scanner;
public class PrintInitials
{
}
// end class PrintInitials
public static void main(String[] args)
{
}
"Enter your first and last name separated by a space: ");
first = stdIn.next();
last = stdIn.next();
System.out.println("Your initials are " +
first.charAt(0) + last.charAt(0) + ".");
// end main
Scanner stdIn = new Scanner(System.in);
String first; // first name
String last;
System.out.print(
Sample session:
// last name
Apago PDF Enhancer
Enter first and last name separated by a space: Malallai Zalmai
Your initials are MZ.
Figure 3.15 PrintInitials program that illustrates next() A Problem with the nextLine Method
The nextLine method and the other Scanner methods don’t play well together. It’s OK to use a series of nextLine method calls in a program. It’s also OK to use a series of nextInt, nextLong, nextFloat, nextDouble, and next method calls in a program. But if you use the nextLine method and the other Scanner methods in the same program, be careful. Here’s why you need to be careful.
The nextLine method is the only method that processes leading whitespace. The other methods skip it. Suppose you have a nextInt method call and the user types 25 and then presses the enter key. The nextInt method call reads the 25 and returns it. The nextInt method call does not read in the enter