Java Reference
In-Depth Information
Display 2.7 Another Keyboard Input Demonstration (part 1 of 2)
1
import java.util.Scanner;
2 public class ScannerDemo2
3{
4
Creates an object of
the class Scanner and
names the object
scannerObject .
public static void main(String[] args)
5
{
6
int n1, n2;
7
Scanner scannerObject = new Scanner(System.in);
8
System.out.println("Enter two whole numbers");
9
System.out.println("separated by one or more spaces:");
Reads one int from the
keyboard.
10
n1 = scannerObject.nextInt();
11
n2 = scannerObject.nextInt();
12
System.out.println("You entered " + n1 + " and " + n2);
13
System.out.println("Next enter two numbers.");
14
System.out.println("Decimal points are allowed.");
Reads one double from
the keyboard.
15
double d1, d2;
16
d1 = scannerObject.nextDouble();
17
d2 = scannerObject.nextDouble();
18
System.out.println("You entered " + d1 + " and " + d2);
19
System.out.println("Next enter two words:");
Reads one word from
the keyboard.
20
String word1 = scannerObject.next();
21
String word2 = scannerObject.next();
22
System.out.println("You entered \"" +
23
word1 + "\" and \"" + word2 + "\"");
24
String junk = scannerObject.nextLine(); //To get rid of '\n'
25
System.out.println("Next enter a line of text:");
This line is
explained in the
Pitfall section
“Dealing with the
Line Terminator,
'\n'
26
String line = scannerObject.nextLine();
27
System.out.println("You entered: \"" + line + "\"");
28
}
29
}
Reads an entire line.
(continued)
Search WWH ::




Custom Search