Documente Academic
Documente Profesional
Documente Cultură
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
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);
S 21
S 22
3.3.
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
apple
orange
pear
The second println statement is improperly indented.
3.5
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"
";+<?"
"^^^^^^^^^^"
"hephalump"
The strings in lexicographic order:
"
"
"******"
"12345"
"6789"
";+<?"
"?-?-?-?"
"Ethel"
"HEPHALUMP"
"Lucy"
"^^^^^^^^^^"
"book"
"bookkeeper"
"fred"
"hephalump"
"ricky"
"{([])}"
2
4
6
8
10
12
14
16
18
3.8
0
2007 Pearson Education
S 23
S 24
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
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++)
S 26
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));
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
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
S 29
S 30
S 31
S 32
//********************************************************************
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
S 33
// 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
{
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
();
("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
S 37
S 38
}
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 + "
" + slot3);
// 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
{
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