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
Creates an object of the class
Scanner and names the
object keyboard .
{
6
Scanner keyboard = new Scanner(System.in);
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();
Each reads one int
from the keyboard
10
int peasPerPod = keyboard.nextInt();
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
The numbers that
are input must be
separated by
whitespace, such as
one or more blanks.
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
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