Java Reference
In-Depth Information
Your program should display
The tickets don't cover all numbers
How do you mark a number as covered? You can create an array with 99 boolean elements.
Each element in the array can be used to mark whether a number is covered. Let the array be
isCovered . Initially, each element is false , as shown in Figure 6.2a. Whenever a number is
read, its corresponding element is set to true . Suppose the numbers entered are 1 , 2 , 3 , 99 ,
0 . When number 1 is read, isCovered[0] is set to true (see Figure 6.2b). When
number 2 is read, isCovered[2 - 1] is set to true (see Figure 6.2c). When number 3 is read,
isCovered[3 - 1] is set to true (see Figure 6.2d). When number 99 is read, isCovered[98]
is set to true (see Figure 6.2e).
isCovered
isCovered
isCovered
isCovered
isCovered
[0]
[1]
[2]
[3]
false
false
false
false
.
.
.
false
false
[0]
[1]
[2]
[3]
true
[0]
[1]
[2]
[3]
true
[0]
[1]
[2]
[3]
true
[0]
[1]
[2]
[3]
true
true
true
false
false
false
.
.
.
false
false
true
true
false
false
.
.
.
false
false
true
false
.
.
.
false
false
false
.
.
.
false
[97]
[98]
[97]
[98]
[97]
[98]
[97]
[98]
[97]
[98]
true
(a)
(b)
(c)
(d)
(e)
F IGURE 6.2
If number i appears in a Lotto ticket, isCovered[i-1] is set to true .
The algorithm for the program can be described as follows:
for each number k read from the file,
mark number k as covered by setting isCovered[k - 1] true;
if every isCovered[i] is true
The tickets cover all numbers
else
The tickets don't cover all numbers
The complete program is given in Listing 6.1.
L ISTING 6.1 LottoNumbers.java
1
import java.util.Scanner;
2
3 public class LottoNumbers {
4 public static void main(String[] args) {
5 Scanner input = new Scanner(System.in);
6
boolean [] isCovered = new boolean [ 99 ]; // Default is false
create and initialize array
7
8 // Read each number and mark its corresponding element covered
9 int number = input.nextInt();
10 while (number != 0 ) {
11 isCovered[number - 1 ] = true ;
12 number = input.nextInt();
13 }
14
read number
mark number covered
read number
 
Search WWH ::




Custom Search