Chapter 2: Objects and Primitive Data Solutions

advertisement
Chapter 2: Objects and Primitive Data
Solutions
Multiple Choice
Solutions
1. c
2. e
3. d
4. b
5. a
6. e
7. b
8. c
9. d
10. b
True/False
Solutions
1. T
2. F
3. T
4. T
5. T
6. F
7. T
8. T
Short Answer Solutions
2.1.
Explain the following programming statement in terms of objects and the services they provide.
System.out.println ("I gotta be me!");
The System.out object has a println method which accepts a string, enclosed in
parentheses and quotation marks, which it displays on the monitor.
2.2.
What output is produced by the following code fragment? Explain.
System.out.print ("Here we go!");
System.out.println ("12345");
System.out.print ("Test this if you are not sure.");
System.out.print ("Another.");
System.out.println ();
System.out.println ("All done.");
The output produced is:
Here we go!12345
Test this if you are not sure.
Another.
All done.
After printing its data, the println method moves to the next line of output,
whereas the print method does not. A println statement with no data has the effect
of moving down to the next line.
2.3.
What is wrong with the following program statement? How can it be fixed?
System.out.println ("To be or not to be, that
is the question.");
S7
S8
Lewis/Loftus/Cocking, 2/e: Chapter 2 Solutions
The string to be printed is not all on one line. The problem can be fixed by
using the string concatenation operator (+) or by using a print statement for part
of the string and a println statement for the remainder of the string.
2.4.
What output is produced by the following statement? Explain.
System.out.println ("50 plus 25 is " + 50 + 25);
The output produced is:
50 plus 25 is 5025
First the string “50 plus 25” is concatenated with the sting “50”; since one of
the operands associated with the “+” operator is a string, the other is treated as
a string. Then the string “50 plus 25 is 50” is concatenated with the string
“25”.
2.5.
What is the output produced by the following statement? Explain.
System.out.println ("He thrusts his fists\n\tagainst" +
" the post\nand still insists\n\the sees the \"ghost\"");
The output produced is:
He thrusts his fists
against the post
and still insists
he sees the “ghost”
Escape characters are used to go to the beginning of new lines (\n), to tab (\t),
and to print quotation marks (\”).
2.6.
Given the following declarations, what result is stored in each of the listed assignment statements?
int iResult, num1 = 25, num2 = 40, num3 = 17, num4 = 5;
double fResult, val1 = 17.0, val2 = 12.78;

iResult = num1 / num4;
iResult is assigned 5

fResult = num1 / num4;
fResult is assigned 5.0

iResult = num3 / num4;
iResult is assigned 3

fResult = num3 / num4;
fResult is assigned 3.0

fResult = val1 / num4;
fResult is assigned 3.4

fResult = val1 / val2;
fResult is assigned 1.3302034...

iResult = num1 / num2;
iResult is assigned 0

fResult = (double) num1 / num2;
fResult is assigned 0.625
Lewis/Loftus/Cocking: Chapter 2 Solutions

S9
fResult = num1 / (double) num2;
fResult is assigned 0.625

fResult = (double) (num1 / num2);
fResult is assigned 0.0

iResult = (int) (val1 / num4);
iResult is assigned 3

fResult = (int) (val1 / num4);
fResult is assigned 3.0

fResult = (int) ((double) num1 / num2);
fResult is assigned 0.0

iResult = num3 % num4;
iResult is assigned 2

iResult = num 2 % num3;
iResult is assigned 6

iResult = num3 % num2;
iResult is assigned 17

iResult = num2 % num4;
iResult is assigned 0
2.7.
For each of the following expressions, indicate the order in which the operators will be evaluated by writing a
number beneath each operator.

a – b – c – d
1

2
a – b + c – d
1

2
1
1
2
3
a % b / c * d
1

2
3
a % b % c % d
1

2
a / b * c * d
1

2
a + b / c * d
3

3
a + b / c / d
3

3
2
3
a – (b – c) – d
2
1
3

(a – (b – c)) – d

a – ((b – c) – d)
2
3
1
1
3
2
S 10
Lewis/Loftus/Cocking, 2/e: Chapter 2
Solutions

a % (b % c) * d * e
2

1
1
2
4
4
3
(a + b) * (c / d) % e
1
2.8.
2
(a + b) * c + d * e
1

4
a + (b – c) * d – e
3

3
3
2
4
Write code to create an enumerated type for the days of the week. Declare a variable of the type you created
and set it equal to Sunday.
enum Day {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}
Day today = Day.Sunday;
2.9.
What output is produced by the following code fragment?
String m1, m2, m3;
m1 = "Quest for the Holy Grail";
m2 = m1.toLowerCase();
m3 = m1 + " " + m2;
System.out.println (m3.replace('h', 'z'));
The output produced is:
Quest for tze Holy Grail quest for tze zoly grail
The original string is concatenated with a lowercase version of itself, then all
lowercase ‘h’ characters are replaced with ‘z’.
2.10.
Write an assignment statement that computes the square root of the sum of num1 and num2 and assigns the
result to num3.
num3 = Math.sqrt(num1 + num2);
2.11.
Write a single statement that computes and prints the absolute value of total.
System.out.println (Math.abs(total));
2.12.
Assuming that a Random object has been created called generator, what is the range of the result of each
of the following expressions?

generator.nextInt(20)
0 to 19, inclusive

generator.nextInt(8) + 1
1 to 8, incluslive

generator.nextInt(45) + 10
10 to 54, inclusive

generator.nextInt(100) – 50
-50 to 49, inclusive
2.13.
Write code to declare and instantiate an object of the Random class (call the object reference variable rand).
Then write a list of expressions using the nextInt method that generate random numbers in the following
Lewis/Loftus/Cocking: Chapter 2 Solutions
S 11
specified ranges, including the endpoints. Use the version of the nextInt method that accepts a single integer
parameter.
Random rand = new Random();

0 to 10
rand.nextInt(11)

0 to 500
rand.nextInt(501)

1 to 10
rand.nextInt(10) + 1

1 to 500
rand.nextInt(500) + 1

25 to 50
rand.nextInt(26) + 25

–10 to 15
rand.nextInt(26) – 10
Programming Project Solutions
2.1 Lincoln
//********************************************************************
// Lincoln4.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 2.1 (page 105).
//********************************************************************
class Lincoln4
{
//----------------------------------------------------------------// Prints a quote from Abraham Lincoln, including quotation
// marks.
//----------------------------------------------------------------public static void main (String[] args)
{
System.out.println ("A quote by Abraham Lincoln:");
System.out.println ("\"Whatever you are, be a good one.\"");
}
}
2.2 AverageOfThree
//********************************************************************
// AverageOfThree.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 2.2
//********************************************************************
import cs1.Keyboard;
class AverageOfThree
{
//----------------------------------------------------------------// Reads three integers from the user and prints their average.
//-----------------------------------------------------------------
S 12
Lewis/Loftus/Cocking, 2/e: Chapter 2
Solutions
public static void main (String[] args)
{
int num1, num2, num3;
double average;
System.out.print ("Enter the first number: ");
num1 = Keyboard.readInt();
System.out.print ("Enter the second number: ");
num2 = Keyboard.readInt();
System.out.print ("Enter the third number: ");
num3 = Keyboard.readInt();
average = (double) (num1+num2+num3) / 3;
System.out.println ("The average is: " + average);
}
}
2.3 FloatCalculations
//********************************************************************
// FloatCalculations.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 2.3
//********************************************************************
import cs1.Keyboard;
class FloatCalculations
{
//----------------------------------------------------------------// Reads two floating point numbers and prints their sum,
// difference, and product.
//----------------------------------------------------------------public static void main (String[] args)
{
float num1, num2;
System.out.print ("Enter the first number: ");
num1 = Keyboard.readFloat();
System.out.print ("Enter the second number: ");
num2 = Keyboard.readFloat();
System.out.println ("Their sum is: " + (num1+num2));
System.out.println ("Their difference is: " + (num1-num2));
System.out.println ("Their product is: " + (num1*num2));
}
}
2.4 TempConverter2
//********************************************************************
// TempConverter2.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 2.4
//********************************************************************
import cs1.Keyboard;
public class TempConverter2
Lewis/Loftus/Cocking: Chapter 2 Solutions
{
//----------------------------------------------------------------// Computes the Celsius equivalent of a Fahrenheit value read
// from the user. Uses the formula C = (5/9)(F - 32).
//----------------------------------------------------------------public static void main (String[] args)
{
final int BASE = 32;
final double CONVERSION_FACTOR = 5.0 / 9.0;
double celsiusTemp, fahrenheitTemp;
System.out.print ("Enter a Fahrenheit temperature: ");
fahrenheitTemp = Keyboard.readDouble();
celsiusTemp = CONVERSION_FACTOR * (fahrenheitTemp - BASE);
System.out.println ("Celsius Equivalent: " + celsiusTemp);
}
}
2.5 MilesToKilometers
//********************************************************************
// MilesToKilometers.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 2.5
//********************************************************************
import cs1.Keyboard;
public class MilesToKilometers
{
//----------------------------------------------------------------// Converts miles into kilometers. The value for miles is read
// from the user.
//----------------------------------------------------------------public static void main (String[] args)
{
final double MILES_PER_KILOMETER = 1.60935;
double miles, kilometers;
System.out.print ("Enter the distance in miles: ");
miles = Keyboard.readDouble();
kilometers = MILES_PER_KILOMETER * miles;
System.out.println ("That distance in kilometers is: " +
kilometers);
}
}
2.6 Seconds
//********************************************************************
// Seconds.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 2.6
//********************************************************************
S 13
S 14
Lewis/Loftus/Cocking, 2/e: Chapter 2
Solutions
import cs1.Keyboard;
public class Seconds
{
//----------------------------------------------------------------// Computes the number of hours, minutes, and seconds that are
// equivalent to the number of seconds entered by the user.
//----------------------------------------------------------------public static void main (String[] args)
{
final int SECONDS_PER_HOUR = 3600;
final int SECONDS_PER_MINUTE = 60;
int seconds, minutes, hours;
System.out.print ("Enter the number of seconds: ");
seconds = Keyboard.readInt();
hours = seconds / SECONDS_PER_HOUR;
seconds = seconds % SECONDS_PER_HOUR;
// still remaining
minutes = seconds / SECONDS_PER_MINUTE;
seconds = seconds % SECONDS_PER_MINUTE;
System.out.println
System.out.println
System.out.println
System.out.println
// still remaining
();
("Hours: " + hours);
("Minutes: " + minutes);
("Seconds: " + seconds);
}
}
2.7 Seconds2
//********************************************************************
// Seconds2.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 2.7
//********************************************************************
import cs1.Keyboard;
public class Seconds2
{
//----------------------------------------------------------------// Computes the total number of seconds for a given number of
// hours, minutes, and seconds.
//----------------------------------------------------------------public static void main (String[] args)
{
final int SECONDS_PER_HOUR = 3600;
final int SECONDS_PER_MINUTE = 60;
int seconds, minutes, hours, totalSeconds;
System.out.print ("Enter the number of hours: ");
hours = Keyboard.readInt();
Lewis/Loftus/Cocking: Chapter 2 Solutions
System.out.print ("Enter the number of minutes: ");
minutes = Keyboard.readInt();
System.out.print ("Enter the number of seconds: ");
seconds = Keyboard.readInt();
totalSeconds = hours * SECONDS_PER_HOUR +
minutes * SECONDS_PER_MINUTE +
seconds;
System.out.println ();
System.out.println ("Total seconds: " + totalSeconds);
}
}
2.8 DistanceCalculation
//********************************************************************
// DistanceCalculation.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 2.8
//********************************************************************
import cs1.Keyboard;
public class DistanceCalculation
{
//----------------------------------------------------------------// Computes the distance between two points using the distance
// formula.
//----------------------------------------------------------------public static void main (String[] args)
{
int x1, y1, x2, y2;
double distance;
System.out.println ("Enter the first coordinate values:");
x1 = Keyboard.readInt();
y1 = Keyboard.readInt();
System.out.println ("Enter the second coordinate values:");
x2 = Keyboard.readInt();
y2 = Keyboard.readInt();
distance = Math.sqrt( Math.pow(x2-x1,2) + Math.pow(y2-y1,2) );
System.out.println ("The distance between (" + x1 + "," + y1 +
") and (" + x2 + "," + y2 + ") is " + distance);
}
}
2.9 SphereCalculations
//********************************************************************
// SphereCalculations.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 2.9
//********************************************************************
import cs1.Keyboard;
S 15
S 16
Lewis/Loftus/Cocking, 2/e: Chapter 2
Solutions
public class SphereCalculations
{
//----------------------------------------------------------------// Computes the volume and surface area of a sphere given its
// radius.
//----------------------------------------------------------------public static void main (String[] args)
{
double radius, area, volume;
System.out.print ("Enter the sphere's radius: ");
radius = Keyboard.readDouble();
volume = 4.0 / 3.0 * Math.PI * Math.pow(radius, 3);
area = 4 * Math.PI * Math.pow(radius, 2);
System.out.println ("Volume: " + volume);
System.out.println ("Surface area: " + area);
}
}
2.10 TriangleArea
//********************************************************************
// TriangleArea.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 2.10
//********************************************************************
import cs1.Keyboard;
import java.text.DecimalFormat;
public class TriangleArea
{
//----------------------------------------------------------------// Computes the area of a triangle given the length of each
// side. Uses Heron's formula.
//----------------------------------------------------------------public static void main (String[] args)
{
double side1, side2, side3, temp, temp2, area;
System.out.print ("Enter the length of side 1: ");
side1 = Keyboard.readDouble();
System.out.print ("Enter the length of side 2: ");
side2 = Keyboard.readDouble();
System.out.print ("Enter the length of side 3: ");
side3 = Keyboard.readDouble();
temp = (side1 + side2 + side3) / 2;
temp2 = temp * (temp-side1) * (temp-side2) * (temp-side3);
area = Math.sqrt (temp2);
DecimalFormat fmt = new DecimalFormat ("0.###");
System.out.println ("Area: " + fmt.format(area));
}
}
2.11 MilesPerGallon
Lewis/Loftus/Cocking: Chapter 2 Solutions
//********************************************************************
// MilesPerGallon.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 2.11
//********************************************************************
import cs1.Keyboard;
import java.text.DecimalFormat;
public class MilesPerGallon
{
//----------------------------------------------------------------// Computes the miles per gallon achieved given the gallons used
// and the odometer readings.
//----------------------------------------------------------------public static void main (String[] args)
{
double gas, mpg;
long odometer1, odometer2;
System.out.print ("Enter the gas used: ");
gas = Keyboard.readDouble();
System.out.print ("Initial odometer reading: ");
odometer1 = Keyboard.readLong();
System.out.print ("Final odometer reading: ");
odometer2 = Keyboard.readLong();
mpg = (odometer2 - odometer1) / gas;
DecimalFormat fmt = new DecimalFormat ("0.##");
System.out.println ("Miles Per Gallon: " + fmt.format(mpg));
}
}
2.12 ChangeCounter
//********************************************************************
// ChangeCounter.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 2.12
//********************************************************************
import cs1.Keyboard;
import java.text.NumberFormat;
public class ChangeCounter
{
//----------------------------------------------------------------// Computes the total value of a collection of coins.
//----------------------------------------------------------------public static void main (String[] args)
{
int quarters, dimes, nickels, pennies;
double total;
System.out.print ("Enter the number of quarters: ");
quarters = Keyboard.readInt();
System.out.print ("Enter the number of dimes: ");
dimes = Keyboard.readInt();
S 17
S 18
Lewis/Loftus/Cocking, 2/e: Chapter 2
Solutions
System.out.print ("Enter the number of nickels: ");
nickels = Keyboard.readInt();
System.out.print ("Enter the number of pennies: ");
pennies = Keyboard.readInt();
total = quarters * 25 + dimes * 10 + nickels * 5 + pennies;
total = total / 100;
NumberFormat fmt = NumberFormat.getCurrencyInstance();
System.out.println ("Total value: " + fmt.format(total));
}
}
2.13 PhoneNumbers
//********************************************************************
// PhoneNumbers.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 2.13
//********************************************************************
import cs1.Keyboard;
import java.text.DecimalFormat;
public class PhoneNumbers
{
//----------------------------------------------------------------// Produces a random phone number with various constraints.
//----------------------------------------------------------------public static void main (String[] args)
{
DecimalFormat fmt = new DecimalFormat ("###");
String result = "";
// none of the first three digits is higher than 7
result += (int) (Math.random() * 8);
result += (int) (Math.random() * 8);
result += (int) (Math.random() * 8);
result += "-";
// then next set of digits cannot be greater than 742
result += (int) (Math.random() * 643) + 100;
result += "-";
result += (int) (Math.random() * 8888) + 1000;
System.out.println ("A random phone number: " + result);
}
}
2.14 Snowman2
//********************************************************************
// Snowman2.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 2.14
//********************************************************************
Lewis/Loftus/Cocking: Chapter 2 Solutions
S 19
import javax.swing.JApplet;
import java.awt.*;
public class Snowman2 extends JApplet
{
//----------------------------------------------------------------// Draws a snowman with added features.
//----------------------------------------------------------------public void paint (Graphics page)
{
final int MID = 130;
final int TOP = 50;
setBackground (Color.cyan);
page.setColor (Color.blue);
page.fillRect (0, 175, 300, 50);
page.setColor (Color.yellow);
page.fillOval (260, -40, 80, 80);
page.setColor
page.fillOval
page.fillOval
page.fillOval
// ground
// sun
(Color.white);
(MID-20, TOP, 40, 40);
(MID-35, TOP+35, 70, 50);
(MID-50, TOP+80, 100, 60);
page.setColor (Color.red);
page.fillOval (MID-3, TOP+50, 6, 6);
page.fillOval (MID-3, TOP+60, 6, 6);
// head
// upper torso
// lower torso
// button
// button
page.setColor (Color.black);
page.fillOval (MID-10, TOP+10, 5, 5);
page.fillOval (MID+5, TOP+10, 5, 5);
// left eye
// right eye
page.drawArc (MID-10, TOP+20, 20, 10, 10, 160);
page.drawLine (MID-25, TOP+60, MID-50, TOP+40);
page.drawLine (MID+25, TOP+60, MID+55, TOP+60);
page.drawLine (MID-20, TOP+5, MID+20, TOP+5);
page.fillRect (MID-15, TOP-20, 30, 25);
page.drawString ("John Lewis", 20, 20);
// frown
// left arm
// right arm
// brim of hat
// top of hat
// artist
}
}
2.15 Face
//********************************************************************
// Face.java
Author: Lewis/Loftus/Cocking
//
// Solution to Programming Project 2.15.
//********************************************************************
import javax.swing.JApplet;
import java.awt.*;
public class Face extends JApplet
S 20
Lewis/Loftus/Cocking, 2/e: Chapter 2
Solutions
{
private
private
private
private
final
final
final
final
int
int
int
int
MIDX = 150;
MIDY = 100;
BASEX = 110;
BASEY = 60;
//----------------------------------------------------------------// Draws a smiling face.
//----------------------------------------------------------------public void paint (Graphics page)
{
setBackground (Color.green);
page.setColor
page.drawOval
page.drawOval
page.drawOval
page.fillOval
page.fillOval
page.drawArc
page.drawArc
page.drawArc
page.drawArc
page.drawArc
page.drawArc
(Color.black);
(MIDX-40, MIDY-40, 80, 80);
(BASEX+20, BASEY+30, 15, 7);
(BASEX+45, BASEY+30, 15, 7);
(BASEX+25, BASEY+31, 5, 5);
(BASEX+50, BASEY+31, 5, 5);
//
//
//
//
//
head
left eye
right eye
left pupil
right pupil
(BASEX+20, BASEY+25, 15, 7, 0, 180); // left eyebrow
(BASEX+45, BASEY+25, 15, 7, 0, 180); // right eyebrow
(BASEX-8, BASEY+35, 16, 15, 90, 180); // left ear
(BASEX+72, BASEY+35, 16, 15, 90, -180); // right ear
(BASEX+35, BASEY+40, 15, 10, 180, 180); // nose
(BASEX+20, BASEY+50, 40, 15, 180, 180); // mouth
}
}
AP-Style Multiple Choice
Solutions
11. D
12. B
13. C
Download