Page 126 - Introduction to Programming with Java: A Problem Solving Approach
P. 126

                92 Chapter 3 Java Basics
 /************************************************************
*
FriendlyHello.java
Dean & Dean
This program displays a personalized Hello greeting.
*************************************************************/
*
*
*
     import java.util.Scanner;
public class FriendlyHello
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
String name;
System.out.print("Enter your name: ");
name = stdIn.nextLine();
System.out.println("Hello " + name + "!");
// end main
Thisgetsalineofinput.
    }
// end class FriendlyHello
}
These two statements create a keyboard-input connection.
Figure 3.13 FriendlyHello program
Apago PDF Enhancer
So why did we bother to use a print statement instead of a println statement for the “Enter your name:” prompt? Because users are used to entering input just to the right of a prompt message. If we used println, then the user would have to enter input on the next line. One additional item: We inserted a colon
and a blank space at the end of the prompt. Once again, the rationale is that that’s what users are used to.
Input Methods
In the FriendlyHello program, we called the Scanner class’s nextLine method to get a line of input. The Scanner class contains quite a few other methods that get different forms of input. Here are some of those methods:
nextInt()
nextLong()
nextFloat()
nextDouble()
next()
Skip leading whitespace until an int value is found. Return the int value.
Skip leading whitespace until a long value is found. Return the long value.
Skip leading whitespace until a float value is found. Return the float value. Skip leading whitespace until a double value is found. Return the double value. Skip leading whitespace until a token is found. Return the token as a String value.
The above descriptions need some clarification:
1. What is leading whitespace?
Whitespace refers to all characters that appear as blanks on a display screen or printer. This includes the space character, the tab character, and the newline character. The newline character is generated with the enter key. Leading whitespace refers to whitespace characters that are at the left side of the input.
























































   124   125   126   127   128