Java Reference
In-Depth Information
If the next input token cannot be expressed as an appropriate number, then the expres-
sions console.nextInt() and console.nextDouble() will cause the program
to terminate with an error message (unless some care is taken in the program), indicating
an input mismatch. For example, if the next input cannot be expressed as an integer, then
the expression console.nextInt() will cause the program to terminate, with the
error message indicating an input mismatch. Examples of invalid integers are 24w5
and 12.50 . Chapter 12 explains why the program terminates with the error message
indicating an input mismatch and how to include the necessary code to handle this
problem. Until then, we assume that the user enters valid numbers.
2
The Java program in Example 2-17 illustrates how to read strings and numeric data.
EXAMPLE 2-17
// This program illustrates how to read strings and numeric data.
import java.util.*;
public class Example2_17
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
String firstName;
//Line 1
String lastName;
//Line 2
int age;
//Line 3
double weight;
//Line 4
System.out.println("Enter first name, last name, "
+ "age, and weight separated "
+ "by spaces.");
//Line 5
firstName = console.next();
//Line 6
lastName = console.next();
//Line 7
age = console.nextInt();
//Line 8
weight = console.nextDouble();
//Line 9
System.out.println("Name: " + firstName
+ " " + lastName);
//Line 10
System.out.println("Age: " + age);
//Line 11
System.out.println("Weight: " + weight);
//Line 12
}
}
 
Search WWH ::




Custom Search