Sie sind auf Seite 1von 20

Chapter 3: Program Statements

Solutions
Multiple Choice
Solutions
1. e
2. d
3. e
4. d
5. c
6. a
7. b
8. c
9. d
10. a

True/False
Solutions
1. T
2. F
3. F
4. F
5. T
6. F
7. T
8. T
9. F

Short Answer Solutions


3.1.

What happens in the MinOfThree program if two or more of the values are equal?
The program still prints the lowest value. Because only less than comparisons are
made, the comparison of two equal values produces a false result. If two values
are equal, and lower than the third value, then one of the two lower but equal
values is printed. If all three values are equal, then this value is printed.
Which version of the equal value is irrelevant.

If exactly two of the values are equal, does it matter whether the equal values are lower or higher than the
third?
The correct result is determined in either case. If the two equal values are lower
than the third, then one of the two lower but equal values is printed. If the two
equal values are higher than the third, then the third value is printed.

3.2.

What is wrong with the following code fragment? Rewrite it so that it produces correct output.
if (total == MAX)
if (total < sum)
System.out.println ("total == MAX and is < sum.");
else
System.out.println ("total is not equal to MAX");
Despite the indentation, the else clause is associated with the immediately
preceding if rather than the first if. The program will produce the correct output
if it is rewritten as:
if (total == MAX)
{
if (total < sum)
System.out.println (total == MAX and is < sum.);
}
else
System.out.println (total is not equal to MAX);

2007 Pearson Education

S 21

S 22

3.3.

Lewis/Loftus/Cocking, 2/e: Chapter 3 Solutions

What is wrong with the following code fragment? Will this code compile if it is part of an otherwise valid
program? Explain.
if (length = MIN_LENGTH)
System.out.println ("The length is minimal.");
The assignment operator (=) is used erroneously in place of the equality operator
(==). Hence, it will not compile in an otherwise valid program.

3.4

What output is produced by the following code fragment?


int num = 87, max = 25;
if (num >= max*2)
System.out.println ("apple");
System.out.println ("orange");
System.out.println ("pear");
The output produced is:

apple
orange
pear
The second println statement is improperly indented.

3.5

What output is produced by the following code fragment?


int limit = 100, num1 = 15, num2 = 40;
if (limit <= limit)
{
if (num1 == num2)
System.out.println ("lemon");
System.out.println ("lime");
}
System.out.println ("grape");
The output is:

lime
grape
3.6

Put the following list of strings in lexicographic order as if determined by the compareTo method of the
String class. Consult the Unicode chart in Appendix C.
"fred"
"Ethel"
"?-?-?-?"
"{([])}"
"Lucy"
"ricky"
"book"
"******"
"12345"
"
"
"HEPHALUMP"
"bookkeeper"
"6789"

2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 3 Solutions

";+<?"
"^^^^^^^^^^"
"hephalump"
The strings in lexicographic order:
"

"

"******"
"12345"
"6789"
";+<?"
"?-?-?-?"
"Ethel"
"HEPHALUMP"
"Lucy"
"^^^^^^^^^^"
"book"
"bookkeeper"
"fred"
"hephalump"
"ricky"
"{([])}"

3.7 What output is produced by the following code fragment?


int num = 1, max = 20;
while (num < max)
{
if (num%2 == 0)
System.out.println (num);
num++;
}
The output produced is:

2
4
6
8
10
12
14
16
18
3.8

What output is produced by the following code fragment?


for (int num = 0; num <= 200; num += 2)
System.out.println (num);
The output produced is:

0
2007 Pearson Education

S 23

S 24

Lewis/Loftus/Cocking, 2/e: Chapter 3 Solutions

2
4
6
.
.
.
198
200
3.9 What output is produced by the following code fragment?
for (int val = 200; val >= 0; val -= 1)
if (val % 4 != 0)
System.out.println (val);
The output produced is:

199
198
197
195
.
.
.
5
3
2
1
3.10 Transform the following while loop into a for loop (make sure it produces the same output).
int num = 1;
while (num < 20)
{
num++;
System.out.println (num);
}
This code can be written using a for loop as follows:
for (int num = 1; num < 20;)
{
num++;
System.out.println (num);
}

3.11 What is wrong with the following code fragment? What are three distinct ways it could be changed to remove the
flaw?
count = 50;
while (count >= 0)
{
System.out.println (count);
count = count + 1;
}
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 3 Solutions

S 25

The loop is infinite because count initially is greater than zero, and continues
to increase in value. The flaw can be removed by (1) decrementing rather than
incrementing count, (2) initializing count to 0 and using, as the condition of the
while loop, count <= 50, and (3) picking an upper limit and using, as the
condition of the while loop, count <= upperLimit.

3.12 Write a while loop that verifies that the user enters a positive integer value.
System.out.print (Enter a positive integer: );
number = scan.nextInt();
while (number <= 0)
{
System.out.print (Enter a positive integer: );
number = scan.nextInt();
}

3.13 Write a code fragment that reads and prints integer values entered by a user until a particular sentinel value
(stored in SENTINEL) is entered. Do not print the sentinel value.
System.out.print (Enter an integer (
+ SENTINEL + to quit): );
number = scan.nextInt();
while (number != SENTINEL)
{
System.out.println (number);
number = scan.nextInt();
}

3.14 Write a for loop to print the odd numbers from 1 to 99 (inclusive).
for (int value = 1; value <= 99; value +=2)
System.out.println (value);

3.15 Write a for loop to print the multiples of 3 from 300 down to 3.
for (int value = 300; value >= 3, value -= 3)
System.out.println (value);

3.16 Write a foreach loop that prints all possible values of an enumerated type called Month.
for (Month m : Month.values())
System.out.println (m);

3.17

Write a code fragment that reads 10 integer values from the user and prints the highest value entered.
int max, number;
System.out.print ("Enter an integer: ");
max = scan.nextInt();
for (int count = 2; count <= 10; count++)
{
System.out.print ("Enter another integer: ");
number = scan.nextInt();
if (number > max)
max = number;
}
System.out.println ("The highest value is :" + max);

3.18

Write a code fragment that determines and prints the number of times the character 'a' appears in a String
object called name.
int count = 0;
for (int position = 0; position < name.length(); position++)

2007 Pearson Education

S 26

Lewis/Loftus/Cocking, 2/e: Chapter 3 Solutions

if (name.charAt(position) == 'a')
count++;
System.out.println ("The character \'a\' appears "
+ count + " time(s)");

3.19

Write a code fragment that prints the characters stored in a String object called str backwards.
for (int position = str.length()-1; position >= 0; position--)
System.out.print (str.charAt(position));
System.out.println();

3.20

Write a code fragment that prints every other character in a String object called word starting with the first
character.
for (int position = 0; position < word.length(); position +=2)
System.out.println(word.charAt(position));

Programming Project Solutions


3.1 Average
//********************************************************************
// Average.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 3.1
//
// Demonstrates the use of a while loop, a sentinel value, and a
// running sum.
//********************************************************************
import java.text.DecimalFormat;
import java.util.Scanner;
public class Average
{
//----------------------------------------------------------------// Computes the average of a set of values entered by the user.
// The running sum is printed as the numbers are entered.
//----------------------------------------------------------------public static void main (String[] args)
{
int sum = 0, value, count = 0;
double average;
Scanner scan = new Scanner(System.in);
System.out.print ("Enter an integer (0 to quit): ");
value = scan.nextInt();
while (value != 0)
{
count++;

// sentinel value of 0 to terminate loop

sum += value;
System.out.println ("The sum so far is " + sum);
System.out.print ("Enter an integer (0 to quit): ");
value = scan.nextInt();
}
System.out.println ();
System.out.println ("Number of values entered: " + count);
if (count < 1)
{
System.out.println("Cannot compute average, no values entered");
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 3 Solutions

S 27

}
else
{
average = (double)sum / count;
DecimalFormat fmt = new DecimalFormat ("0.###");
System.out.println ("The average is " + fmt.format(average));
}
}
}
3.2 LeapYear
//********************************************************************
// LeapYear.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 3.2
//
// Reads an integer value representing a year. Determines if the year
// is a leap year
//********************************************************************
import java.util.Scanner;
public class LeapYear
{
//----------------------------------------------------------------// Reads an integer value representing a year. Determines if the year
// is a leap year
//----------------------------------------------------------------public static void main (String[] args)
{
int year;
boolean leap = false;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a year : ");
year = scan.nextInt();
if (year < 1582)
System.out.println("ERROR year not valid in the Gregorian calendar");
else
{
if (year % 4 == 0) // divisible by 4
{
leap = true;
if ((year % 100 == 0) && (year % 400 != 0))
{
leap = false;
}
}
if (leap)
System.out.println(year + " is a leap year");
else
System.out.println(year + " is not a leap year");
}
}
}
3.3 LeapYear2
//********************************************************************
// LeapYear2.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 3.3
//
2007 Pearson Education

S 28

Lewis/Loftus/Cocking, 2/e: Chapter 3 Solutions

// Determines if a year is a leap year.


//********************************************************************
import java.util.Scanner;
public class LeapYear2
{
//----------------------------------------------------------------// Reads an integer value representing a year. Determines if the year
// is a leap year. Prompts the user to enter another year or quit.
//----------------------------------------------------------------public static void main (String[] args)
{
int year;
boolean leap = false;
Scanner scan = new Scanner(System.in);
do
{
System.out.print("\nEnter a year (0 to quit): ");
year = scan.nextInt();
if (year != 0)
{
if (year < 1582)
System.out.println("ERROR year not valid in the Gregorian
calendar");
else
{
if (year % 4 == 0) // divisible by 4
{
leap = true;
if ((year % 100 == 0) && (year % 400 != 0))
{
leap = false;
}
}
if (leap)
System.out.println(year + " is a leap year");
else
System.out.println(year + " is not a leap year");
}
}
leap = false;
} while (year !=0);
}
}
3.4 SumEvens
//********************************************************************
// SumEvens.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 3.4
//********************************************************************
import java.util.Scanner;
public class SumEvens
{
//----------------------------------------------------------------// Computes and prints the sum of the even values between 2 and
// a positive value entered by the user.
//----------------------------------------------------------------public static void main (String[] args)
{
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 3 Solutions

int sum = 0, value;


Scanner scan = new Scanner(System.in);
System.out.print ("Enter a positive integer: ");
value = scan.nextInt();
if (value < 2)
System.out.println ("The value must be greater than two.");
else
{
for (int count = 2; count <= value; count+=2)
sum += count;
System.out.println ("The sum of the even integers from 2 to "
+ value + " is " + sum);
}
}
}
3.5 StringDown
//********************************************************************
// StringDown.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 3.5
//********************************************************************
import java.util.Scanner;
public class StringDown
{
//----------------------------------------------------------------// Reads a string from the user and prints it one character
// per line.
//----------------------------------------------------------------public static void main (String[] args)
{
String str;
Scanner scan = new Scanner(System.in);
System.out.println ("Enter a string of characters:");
str = scan.nextLine();
for (int index=0; index < str.length(); index++)
System.out.println (str.charAt(index));
}
}
3.6 CountDigits
//********************************************************************
// CountDigits.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 3.6
//********************************************************************
import java.util.Scanner;
public class CountDigits
{
//----------------------------------------------------------------// Counts the number of odd, even, and zero digits in an
// integer input value.
//----------------------------------------------------------------public static void main (String[] args)
{
int oddCount = 0, evenCount = 0, zeroCount = 0;
int value, digit;
2007 Pearson Education

S 29

S 30

Lewis/Loftus/Cocking, 2/e: Chapter 3 Solutions

Scanner scan = new Scanner(System.in);


System.out.print ("Enter an integer value: ");
value = scan.nextInt();
value = Math.abs (value);
if (value == 0)
zeroCount++;
while (value > 0)
{
digit = value % 10;
if (digit == 0)
zeroCount++;
else
if (digit%2 == 0)
evenCount++;
else
oddCount++;
value = value / 10;
}
System.out.println ("Zero digits: " + zeroCount);
System.out.println ("Even digits: " + evenCount);
System.out.println ("Odd digits: " + oddCount);
}
}
3.7 MultTable
//********************************************************************
// MultTable.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 3.7
//********************************************************************
public class MultTable
{
//----------------------------------------------------------------// Prints a multiplication table.
//----------------------------------------------------------------public static void main (String[] args)
{
final int MAX = 12;
for (int row = 1; row <= MAX; row++)
{
for (int column = 1; column <= MAX; column++)
System.out.print (row*column + "\t");
System.out.println();
}
}
}
3.8 Counter4
//********************************************************************
// Counter4.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 3.8
//********************************************************************
public class Counter4
{
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 3 Solutions

//----------------------------------------------------------------// Prints integer values from 1 to a specific limit.


//----------------------------------------------------------------public static void main (String[] args)
{
final int LIMIT = 5;
int count = 1;
do
{
System.out.println (count);
count = count + 1;
}
while (count <= LIMIT);
System.out.println ("Done");
}
}
3.9 TravelSong
//********************************************************************
// TravelingSong.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 3.9.
//********************************************************************
import java.util.Scanner;
public class TravelingSong
{
//----------------------------------------------------------------// Prints the first few verses of "100 Bottles of Beer"
//----------------------------------------------------------------public static void main (String[] args)
{
final int MAX = 100;
int numVerses = 0; // number of verses to print
Scanner scan = new Scanner(System.in);
while (numVerses < 1 || numVerses > MAX)
{
System.out.print ("How many verses (1 to " + MAX + ")? ");
numVerses = scan.nextInt();
}
int count = MAX;
for (int verse = 1; verse <= numVerses; verse++)
{
System.out.println (count + " bottles of beer on the wall.");
System.out.println (count + " bottles of beer.");
System.out.println ("If one of those bottles should happen "
+ "to fall");
count = count - 1;
System.out.println (count + " bottles of beer on the wall.");
System.out.println ();
}
}
}
3.10 HiLo
//********************************************************************
// HiLo.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 3.10
2007 Pearson Education

S 31

S 32

Lewis/Loftus/Cocking, 2/e: Chapter 3 Solutions

//********************************************************************
import java.util.Scanner;
public class HiLo
{
//----------------------------------------------------------------// Randomly selects a number in a particular range, which the
// user attempts to guess.
//----------------------------------------------------------------public static void main (String[] args)
{
final int MAX = 100;
int target, count = 0, guess;
String again;
Scanner scan = new Scanner(System.in);
do
{
System.out.println();
System.out.println ("Guess a number between 1 and " + MAX);
target = (int) (Math.random() * MAX) + 1;
do
{
System.out.println();
System.out.print ("Enter your guess (0 to quit): ");
guess = scan.nextInt();
count = count + 1;
if (guess > 0)
if (guess == target)
System.out.println ("Right! Guesses: " + count);
else
if (guess < target)
System.out.println ("Your guess was too LOW.");
else
System.out.println ("Your guess was too HIGH.");
}
while (guess != target && guess > 0);
System.out.println();
System.out.print ("Play again (y/n)?: ");
again = scan.nextLine();
}
while (again.equalsIgnoreCase ("y"));
}
}
3.11 PalindromeTester
//********************************************************************
// PalindromeTester.java
Author: Lewis/Loftus/Cocking
//
// Demonstrates the use of nested while loops.
//********************************************************************
import java.util.Scanner;
public class PalindromeTester
{
//----------------------------------------------------------------// Removes whitespace and punction from a string. Converts all
// characters to lowercase.
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 3 Solutions

S 33

//----------------------------------------------------------------private static String convertString(String s)


{
String converted = "";
char current;
for (int i=0; i<s.length(); i++)
{
current = s.charAt(i);
if (Character.isLetterOrDigit(current)) // only count letters and
digits
{
if (Character.isUpperCase(current))

// convert to lowercase if

needed
current = Character.toLowerCase(current);
converted += current;
}
}
return converted;
}
//----------------------------------------------------------------// Tests strings to see if they are palindromes.
//----------------------------------------------------------------public static void main (String[] args)
{
String str, another = "y";
int left, right;
Scanner scan = new Scanner(System.in);
while (another.equalsIgnoreCase("y")) // allows y or Y
{
System.out.println ("Enter a potential palindrome:");
str = convertString(scan.nextLine());
left = 0;
right = str.length() - 1;
while (str.charAt(left) == str.charAt(right) && left < right)
{
left++;
right--;
}
System.out.println();
if (left < right)
System.out.println ("That string is NOT a palindrome.");
else
System.out.println ("That string IS a palindrome.");
System.out.println();
System.out.print ("Test another palindrome (y/n)? ");
another = scan.nextLine();
}
}
}
3.12a Stars2
//********************************************************************
// Stars2.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 3.12a
//********************************************************************
2007 Pearson Education

S 34

Lewis/Loftus/Cocking, 2/e: Chapter 3 Solutions

public class Stars2


{
//----------------------------------------------------------------// Prints a triangle shape using asterisk (star) characters.
//----------------------------------------------------------------public static void main (String[] args)
{
final int LIMIT = 10;
for (int row = 1; row <= LIMIT; row++)
{
for (int star = 1; star <= LIMIT-row+1; star++)
System.out.print ("*");
System.out.println();
}
}
}
3.12b Stars3
//********************************************************************
// Stars3.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 3.12b
//********************************************************************
public class Stars3
{
//----------------------------------------------------------------// Prints a triangle shape using asterisk (star) characters.
//----------------------------------------------------------------public static void main (String[] args)
{
final int LIMIT = 10;
for (int row = 1; row <= LIMIT; row++)
{
for (int space = 1; space <= LIMIT-row; space++)
System.out.print (" ");
for (int star = 1; star <= row; star++)
System.out.print ("*");
System.out.println();
}
}
}
3.12c Stars4
//********************************************************************
// Stars4.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 3.12c
//********************************************************************
public class Stars4
{
//----------------------------------------------------------------// Prints a triangle shape using asterisk (star) characters.
//----------------------------------------------------------------public static void main (String[] args)
{
final int LIMIT = 10;
for (int row = 1; row <= LIMIT; row++)
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 3 Solutions

{
for (int space = 1; space <= row-1; space++)
System.out.print (" ");
for (int star = 1; star <= LIMIT-row+1; star++)
System.out.print ("*");
System.out.println();
}
}
}
3.12d Stars5
//********************************************************************
// Stars5.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 3.12d
//********************************************************************
public class Stars5
{
//----------------------------------------------------------------// Prints a diamond shape using asterisk (star) characters.
//----------------------------------------------------------------public static void main (String[] args)
{
final int LIMIT = 10;
// Print top half of diamond
for (int row = 1; row <= LIMIT/2; row++)
{
for (int space = 1; space <= (LIMIT/2)-row; space++)
System.out.print (" ");
for (int star = 1; star <= (row*2)-1; star++)
System.out.print ("*");
System.out.println();
}
// Print bottom half of diamond
for (int row = 1; row <= LIMIT/2; row++)
{
for (int space = 1; space <= row-1; space++)
System.out.print (" ");
for (int star = 1; star <= LIMIT-(row*2)+1; star++)
System.out.print ("*");
System.out.println();
}
}
}
3.13 Vowels
//********************************************************************
// Vowels.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 3.13
//********************************************************************
import java.util.Scanner;
public class Vowels
{
2007 Pearson Education

S 35

S 36

Lewis/Loftus/Cocking, 2/e: Chapter 3 Solutions

//----------------------------------------------------------------// Counts the number of each vowel in a string.


//----------------------------------------------------------------public static void main (String[] args)
{
int acount = 0, ecount = 0, icount = 0, ocount = 0, ucount = 0;
int other = 0;
Scanner scan = new Scanner(System.in);
System.out.println ("Enter a string of characters:");
String str = scan.nextLine();
str = str.toLowerCase();

// for consistent counting

for (int index = 0; index < str.length(); index++)


{
switch (str.charAt (index))
{
case 'a':
acount++;
break;
case 'e':
ecount++;
break;
case 'i':
icount++;
break;
case 'o':
ocount++;
break;
case 'u':
ucount++;
break;
default:
other++;
}
}
System.out.println
System.out.println
System.out.println
System.out.println
System.out.println
System.out.println
System.out.println
System.out.println

();
("Number of each vowel in the string:");
("a: " + acount);
("e: " + ecount);
("i: " + icount);
("o: " + ocount);
("u: " + ucount);
("other characters: " + other);

}
}
3.14 RockPaperScissors
//********************************************************************
// RockPaperScissors.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 3.14
//********************************************************************
import java.util.Scanner;
public class RockPaperScissors
{
//----------------------------------------------------------------// Plays the Rock-Paper-Scissors game with the user.
//----------------------------------------------------------------public static void main (String[] args)
{
final int OPTIONS = 3;
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 3 Solutions

final int ROCK = 1, PAPER = 2, SCISSORS = 3;


final int COMPUTER = 1, PLAYER = 2, TIE = 3;
int computer, player, winner = 0;
int wins = 0, losses = 0, ties = 0;
String again;
Scanner scan = new Scanner(System.in);
do
{
computer = (int) (Math.random() * OPTIONS) + 1;
System.out.println();
System.out.print ("Enter your choice - 1 for Rock, 2 for " +
"Paper, and 3 for Scissors: ");
player = scan.nextInt();
System.out.print ("My choice was ");
// Determine the winner
switch (computer)
{
case ROCK:
System.out.println ("Rock.");
if (player == SCISSORS)
winner = COMPUTER;
else
if (player == PAPER)
winner = PLAYER;
else
winner = TIE;
break;
case PAPER:
System.out.println ("Paper.");
if (player == ROCK)
winner = COMPUTER;
else
if (player == SCISSORS)
winner = PLAYER;
else
winner = TIE;
break;
case SCISSORS:
System.out.println ("Scissors.");
if (player == PAPER)
winner = COMPUTER;
else
if (player == ROCK)
winner = PLAYER;
else
winner = TIE;
}
// Print results and increment appropriate counter
if (winner == COMPUTER)
{
System.out.println ("I win!");
losses++;
}
else
if (winner == PLAYER)
{
System.out.println ("You win!");
wins++;
2007 Pearson Education

S 37

S 38

Lewis/Loftus/Cocking, 2/e: Chapter 3 Solutions

}
else
{
System.out.println ("We tied!");
ties++;
}
System.out.println();
System.out.print ("Play again (y/n)?: ");
again = scan.nextLine();
}
while (again.equalsIgnoreCase ("y"));
// Print final results
System.out.println();
System.out.println ("You won " + wins + " times.");
System.out.println ("You lost " + losses + " times.");
System.out.println ("We tied " + ties + " times.");
}
}
3.15 SimpleSlot
//********************************************************************
// SimpleSlot.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 3.15
//********************************************************************
import java.util.Scanner;
public class SimpleSlot
{
//----------------------------------------------------------------// Plays a simple slot machine using digits.
//----------------------------------------------------------------public static void main (String[] args)
{
final int DIGITS = 10;
int slot1, slot2, slot3;
String again;
Scanner scan = new Scanner(System.in);
do
{
slot1 = (int) (Math.random() * DIGITS);
slot2 = (int) (Math.random() * DIGITS);
slot3 = (int) (Math.random() * DIGITS);
System.out.println (slot1 + "

" + slot2 + "

" + slot3);

if (slot1 == slot2 && slot2 == slot3)


System.out.println ("Jackpot!!!");
else
if (slot1 == slot2 || slot2 == slot3 || slot1 == slot3)
System.out.println ("Matched 2!!");
System.out.println();
System.out.print ("Play again (y/n)?: ");
again = scan.nextLine();
}
while (again.equalsIgnoreCase ("y"));
}
}
3.16 StairSteps
//********************************************************************
2007 Pearson Education

Lewis/Loftus/Cocking, 2/e: Chapter 3 Solutions

// StairSteps.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 3.16
//********************************************************************
import javax.swing.JApplet;
import java.awt.*;
public class StairSteps extends JApplet
{
private final int NUM_STEPS = 15;
private final int STAIR_HEIGHT = 15;
private final int STAIR_DEPTH = 15;
private final int START_X = 20;
private final int START_Y = 300 - STAIR_DEPTH;
//----------------------------------------------------------------// Paints a side view of some stair steps.
//----------------------------------------------------------------public void paint(Graphics page)
{
int stepX = START_X, stepY = START_Y;
setBackground (Color.cyan);
page.setColor (Color.black);
for (int count=1; count <= NUM_STEPS; count++)
{
page.drawLine (stepX, stepY, stepX, stepY + STAIR_HEIGHT);
page.drawLine (stepX, stepY, stepX + STAIR_DEPTH, stepY);
stepX += STAIR_DEPTH;
stepY -= STAIR_HEIGHT;
}
}
}
3.17 ColoredCircles
//********************************************************************
// ColoredCircles.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 3.17
//********************************************************************
import javax.swing.JApplet;
import java.awt.*;
public class ColoredCircles extends JApplet
{
private final int NUM_CIRCLES = 100;
private final int MIN_DIAMETER = 5;
private final int MAX_DIAMETER = 30;
private final int MAX_COLORVALUE = 256;
private final int MAX_X = 370;
private final int MAX_Y = 170;
//----------------------------------------------------------------// Paints several circles of random color, diameter, and location.
//----------------------------------------------------------------public void paint(Graphics page)
{
int x, y, diameter, red, green, blue;
setBackground (Color.black);
for (int count=1; count <= NUM_CIRCLES; count++)
2007 Pearson Education

S 39

S 40

Lewis/Loftus/Cocking, 2/e: Chapter 3 Solutions

{
x = (int) (Math.random() * MAX_X);
y = (int) (Math.random() * MAX_Y);
red = (int) (Math.random() * MAX_COLORVALUE);
green = (int) (Math.random() * MAX_COLORVALUE);
blue = (int) (Math.random() * MAX_COLORVALUE);
page.setColor (new Color(red, green, blue));
diameter = (int) (Math.random() * MAX_DIAMETER) + MIN_DIAMETER;
page.drawOval (x, y, diameter, diameter);
}
}
}
AP-Style Multiple Choice
Solutions
1. D
2. A
3. A
4. E
5. D
6. C

2007 Pearson Education