Java Reference
In-Depth Information
Display 2.6
Keyboard Input Demonstration
1 import java.util.Scanner;
Makes the Scanner class available
to your program.
2 public class ScannerDemo
3 {
4 public static void main(String[] args)
5 {
6 Scanner keyboard = new Scanner(System.in);
Creates an object of the class
Scanner and names the
object keyboard .
7 System.out.println("Enter the number of pods followed by");
8 System.out.println("the number of peas in a pod:");
9 int numberOfPods = keyboard.nextInt();
10 int peasPerPod = keyboard.nextInt();
Each reads one int
from the keyboard
11 int totalNumberOfPeas = numberOfPods*peasPerPod;
12 System.out.print(numberOfPods + " pods and ");
13 System.out.println(peasPerPod + " peas per pod.");
14 System.out.println("The total number of peas = "
15 + totalNumberOfPeas);
16 }
17 }
Sample Dialogue 1
Enter the number of pods followed by
the number of peas in a pod:
22 10
22 pods and 10 peas per pod.
The total number of peas = 220
The numbers that
are input must be
separated by
whitespace, such as
one or more blanks.
Sample Dialogue 2
Enter the number of pods followed by
the number of peas in a pod:
22
10
22 pods and 10 peas per pod.
The total number of peas = 220
A line break is also
considered whitespace and
can be used to separate the
numbers typed in at the
keyboard.
 
 
Search WWH ::




Custom Search