0% found this document useful (0 votes)
19 views13 pages

Solutions ch03

Java
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views13 pages

Solutions ch03

Java
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 13

Chapter 3 Solutions

1. Suppose we have the following declarations:

int i = 3, j = 4, k = 5;
float x = 34.5f, y = 12.25f;

Determine the value for each of the following expressions or explain why it is not a valid
expression.

a. (x + 1.5) / (250.0 * (i/j)) f. Math.exp(3,


2)
b. x + 1.5 / 250.0 * i / j g. y % x
c. –x * -y * (i + j) / k h. Math.pow(3,
2)
d. (i / 5) * y i. (int)y % k
e. Math.min(I, Math.min(j,k)) j. i / 5 * y

a. undefined (i/j) evaluates 0 resulting in division by 0.


Note: if you actually execute this expression, Java
will return the value Infinity.

b. 34.5045

c. 591.675f

d. 0 (i/5) evaluates to 0.

e. 3

f. Invalid. No such method

g. 12.25

h. 9.0

i. 2

j. 0.0f

2. Suppose we have the following declarations:

int m, n, i = 3, j = 4, k = 5;
float v, w, x = 34.5f, y = 12.25f
Determine the value assigned to the variable in each of the following assignment
statements or explain why it is not a valid assignment.

a. w = Math.pow(3, Math.pow(i,j));
b. v = x / i;
c. w = Math.ceil(y) % k;
d. n = (int) x / y * i / 2;
e. x = Math.sqrt(i*i – 4*j*k);
f. m = n + i * j;
g. n = k /(j * i) * x + y
h. i = i + 1;
i. w = float(x + i);
j. x = x / i / y / j;

a. Expression value: 4.34264882430377E38


Not a valid assignment. Compilation error due to the possible loss of precision
(assigning a double value to a float variable)

b. 11.5f

c. Expression value: 3.0f


Not a valid assignment. Compilation error due to the possible loss of precision
(assigning a double value to a float variable)

d. Expression value: 4.163265f


Not a valid assignment. Compilation error due to the possible loss of precision
(assigning a float value to an int variable)

e. Expression value: NaN (or not a number because you can’t take the square root of a
negative number)
Not a valid assignment. Compilation error due to the possible loss of precision
(assigning a double value to a float variable)

f. Invalid Variable n has no value assigned.

g. Expression value: 12/25f


Not a valid assignment. Compilation error due to the possible loss of precision
(assigning a float value to an int variable)

h. 4

i.Invalid syntax

j. 0.23469388f
3. Suppose we have the following declarations:

int i, j;
float x, y;
double u, v;

Which of the following assignments are valid?

a. i = x;
b. x = u + y;
c. x = 23.4 + j * y;
d. v = (int) x;
e. y = j / i * x;

a. Invalid Cannot assign a float value to an int variable.


Variable x is not initialized.

b. Invalid Cannot assign a double value to a float variable.


Variables u and y are not initialized.

c. Invalid Cannot assign a double value to a float variable.


Variables j and y are not initialized.

d. Invalid Variable x is not initialized. If it is initialized, then


this expression is valid.

e. Invalid Variables i, j, and x are not initialized. If they are


initialized, then this expression is valid.

4. Write Java expressions to compute each of the following:

a. The square root of B2 + 4AC (A and C are distinct variables)


b. The square root of X + 4Y3
c. The cube root of the product of X and Y
d. The area πR2 of a circle

a.
Math.sqrt(B*B + 4*A*C)

b.
Math.sqrt(X + 4*Y*Y*Y) or
Math.sqrt(X + 4 * Math.pow(Y, 3))
c.
Math.pow(X*Y, 1.0/3.0)

d.
Math.PI * R * R
5. Determine the output of the following program without running it:

class TestOutputBox {
public static void main(String[] args) {
System.out.println("One");
System.out.print("Two");
System.out.print("\n");

System.out.print("Three");
System.out.println("Four");
System.out.print("\n");

System.out.print("Five");
System.out.println("Six");
}
}

One
Two
ThreeFour

FiveSix

6. Determine the output of the following code:

int x, y;
x = 1;
y = 2;
System.out.println("The output is " + x + y);
System.out.println("The output is " + (x + y) );

The output is 12
The output is 3

Level 1 Programming Exercises

7. Write a program to convert centimeters (input) to feet and inches


(output). 1 in = 2.54 cm.

See Exercise3_7.java.
8. Write a program that inputs temperature in degrees Celsius and prints out
the temperature in degrees Fahrenheit. The formula to convert degrees Celsius to the
equivalent degrees Fahrenheit is

Fahrenheit = 1.8 * Celsius + 32

See Exercise3_8.java.

9. Write a program that accepts a person’s weight and displays the number of
calories the person needs in one day. A person needs 19 calories per pound of body
weight, so the formula expressed in Java is

calories = bodyweight * 19;

(Note: We are not distinguishing between genders.)

See Exercise3_9.java.

10. Write a program that does the reverse of Exercise 8, that is, input degrees
Fahrenheit and prints out the temperature in degree Celsius. The formula to convert
degrees Fahrenheit to equivalent degrees Celsius is

Celsius = 5/9 * (Fahrenheit – 32)

See Exercise3_10.java.

11. Write a program that inputs the year a person is born and outputs the age
of the person in the following format

You were born in 1990 and will be (are) 18 this year.

See Exercise3_11.java.

12. A quantity known as the body mass index (BMI) is used to calculate the
risk of weight-related health problems. BMI is computed by the formula

BMI = w / (h / 100.0)2

where w is height in kilograms and h is height in centimeters. A BMI of about 20 to 25 is


considered “normal.” Write a program that accepts weight and height (both integers) and
outputs the BMI.

See Exercise3_12.java

13. If you invest P dollars at R percent interest rate compounded annually, in


N years, your investment will grow to
P(1 + R/100)N

dollars. Write an application that accepts P, R, and N and computes the amount of money
earned after N years.

See Exercise3_13.java.

14. The volume of a sphere is computed by the equation

where V is the volume and r is the radius of the sphere. Write a program that computes
the volume of a sphere with a given radius r.

See Exercise3_14.java.

Level 2 Programming Exercises

15. The velocity of a satellite circling around the Earth is computed by the
formula

where ME = 5.98 * 1024kg is the mass of the Earth, r the distance from the center of the
Earth to the satellite in meters, and G = 6.67 * 10-11 m3/(kg * s2) the universal
gravitational constant. The unit of the velocity v is m/s. Write a program that inputs the
radius r and outputs the satellite’s velocity. Confirm that a satellite that is closer to the
Earth travels faster. Define symbolic constants for ME and G. The distance to the Hubble
telescope from the center of the Earth, for example, is approximately 6.98 * 106m.

See Exercise3_15.java.

16. Your weight is actually the amount of gravitational attraction exerted on


you by the earth. Since the Moon’s gravity is only one-sixth of the earth’s gravity, on the
Moon you would weigh only one-sixth of what you weigh on earth. Write a program that
inputs the user’s earth weight and outputs her or his weight on Mercury, Venus, Jupiter,
and Saturn. Use your preferred choice for input and output. Use the values in this table.

Planet Multiply the Earth Weight by


Mercury 0.4
Venus 0.9
Jupiter 2.5
Saturn 1.1

See Exercise3_16.java.
17. When you say you are 18 years old, you are really saying that the Earth
has circled the Sun 18 times. Since other planets take fewer or more days than earth to
travel around the sun, your age would be different on other planets. You can compute
how old you are on other planets by the formula

y = x * 365 / d

where x is the age on the Earth, y is the age on planet Y, and d is the number of Earth
days the planet Y takes to travel around the Sun. Write a program that inputs the user’s
Earth age and prints out his or her age on Mercury, Venus, Jupiter, and Saturn. The
values for d are listed in the table.

d = Approximate Number of
Earth Days for This Planet to
Planet Travel around the Sun
Mercury 88
Venus 225
Jupiter 4380
Saturn 10767

See Exercise3_17.java.

18. Write a program to solve quadratic equations of the form

Ax2 + Bx + C = 0

where the coefficients A, B, and C are real numbers. The two real number solutions are
derived by the formula

For this exercise, you may assume that A 0 and the relationship

B2 4AC

holds, so there will be real number solutions for x.

See Exercise3_18.java.

19. Write a program that determines the number of days in a given semester.
Input to the program is the year, month, and day information of the first and the last days
of a semester. Hint: Create GregorianCalendar objects for the start and end dates
of a semester and manipulate their DAY_OF_YEAR data.
See Exercise3_19.java.

20. Modify the Ch3FindDayOfWeek program by accepting the date


information as a single string instead of accepting the year, month, and day information
separately. The input string must be in the MM/dd/yyyy format. For example, July 4,
1776, is entered as 07/04/1776. There will be exactly two digits for the month and day
and four digits for the year.

See Exercise3_20.java.

21. Leonardo Fibonacci of Pisa was one of the greatest mathematicians of the
Middle Ages. He is perhaps most famous for the Fibonacci sequence, which can be
applied to many diverse problems. One amusing application of the Fibonacci sequence is
in finding the growth rate of rabbits. Suppose a pair of rabbits matures in 2 months and is
capable of reproducing another pair every month after maturity. If every new pair has the
same capability, how many pairs will there be after 1 year? (We assume here that no
pairs die.) The table below shows the sequence for the first 7 months. Notice that at the
end of the second month, the first pair matures and bears its first offspring in the third
month, making the total two pairs.

The Nth Fibonacci number in the sequence can be evaluated with the formula

Write a program that accepts N and displays FN. Note that the result of computation
using the Math class is double. You need to display it as an integer.

See Exercise3_21.java.

22. According to Newton’s universal law of gravitation, the force F between


two bodies with masses M1 and M2 is computed as
where d is the distance between the two bodies and k is a positive real number called the
gravitational constant. The gravitational constant k is approximately equal to 6.67E-8
dyn * cm2/g2.
Write a program that (1) accepts the mass for two bodies in grams and the distance
between the two bodies in centimeters, and (2) computes the force F. Use the standard
input and output, and format the output appropriately. For your information, the force
between the earth and the moon is 1.984E25 dyn. The mass of the earth is 5.983R27 g,
the mass of the moon is 7.347E25g, and the distance between the two is 3.844E10 cm.

See Exercise3_22.java.

23. Dr. Caffeine’s Law of Program Readability states that the degree of
program readability R (whose unit is mocha) is determined as

where k is Ms. Latte’s constant, C is the number of lines in the program that contain
comments, T is the time spent (in minutes) by the programmer developing the program,
and V is the number if lines in the program that contain nondescriptive variable names.
Write a program to compute the program readability R. Ms. Latte’s constant is 2.5E2
mocha lines2/min2. (Note: This is just for fun. Develop your own law, using various
functions from the Math class.)

See Exercise3_23.java.

Level 3 Programming Exercises

24. Write a program that accepts the unit weight of a bag of coffee in pounds
and the number of bags sold and displays the total price of the sale, computed as

totalPrice = unitWeight * numberOfUnits * 5.99;


totalPriceWithTax = totalPrice + totalPrice * 0.0725;

where 5.99 is the cost per pound and 0.0725 is the sales tax. Display the result in the
following manner:

Draw the program diagram.


See Exercise3_24.java.

25. If the population of a country grows according to the formula

y = cekx

where y is the population after x years from the reference year, then we can determine the
population of a country for a given year from two census figures. For example, given
that a country with a population of 1,000,000 in 1970 grows to 2,000,000 by 1990, we
can predict the country’s population in the year 2000. Here’s how we do the
computation. Letting x be the number of years after 1970, we obtain the constant c as
1,000,000 because

1,000,000 = cek0 = c

Then we determine the value of k as

y = 1,000,000ekx

2,000,000 / 1,000,000 = e20k

k = (1/20)ln(2,000,000/1,000,000) = 0.03466

Finally we can predict the population in the year 2000 by substituting 0.03466 for k and
30 for x (2000 – 1970 = 30). Thus we predict

y = 1,000,000e0.03466(30) = 2,828,651

as the population of the country for the year 2000. Write a program that accepts five
input values – year A, the population in year A, year B, population in year B, and year C
– and predict the population for year C.

See Exercise3_25.java.

26. In section 3.9, we use the formula

MR = AR / 12

to derive the monthly interest rate from a given annual interest rate, where MR is the
monthly interest rate and AR is the annual interest rate (expressed in a fractional value
such as 0.083). This annual interest rate AR is called the stated annual interest rate to
distinguish it from the effective annual interest rate, which is the true cost of a loan. If
the stated annual interest rate is 9 percent, for example, the effective annual interest rate
is actually 9.38 percent. Naturally, the rate that the financial institutions advertise more
prominently is the stated interest rate. The load calculator program in section 3.10 treats
the annual interest rate that the user enters as the stated annual interest rate. If the input is
the effective annual interest rate, then we compute the monthly rate as

MR = (1 + EAR)1/12 – 1

where EAR is the effective annual interest rate. The difference between the stated and
effective annual interest rates is negligible only when the load amount is small or the load
period is short. Modify the loan calculator program so that the interest rate that the user
enters is treated as the effective annual interest rate. Run the original and modified loan
calculator programs, and compare the difference in the monthly and total payments. Use
the load amount of 1, 10 and 50 million dollars with the load period of 10, 20, and 30
years and annual interest rates of 0.07, 0.10 and 0.18 respectively. Try other
combinations also.
Visit several websites that provide a loan calculator for computing a monthly
mortgage payment (one such site is the financial page at www.cnn.com). Compare your
results to the values computed by the websites you visited. Determine whether the
websites treat the input annual interest rate as stated or effective.

See Exercise3_26.java.

27. Ask the user to enter his or her birthday in the MM/DD/YYYY format and
output the number of days between the birthday and today. This gives the person how
many days old is he or she.

See Exercise3_27.java.

Development Exercises

28. Develop an application that reads a purchase price and an amount tendered
and then displays the change in dollars, quarters, dimes, nickels, and pennies. Two input
values are entered in cents, for example, 3480 for $34.80 and 70 for $0.70. Display the
output in the following format:
Notice the input values are to be entered in cents (int data type), but the echo printed
values must be displayed with decimal points (float data type).

See Exercise3_28.java.

29. MyJava Coffee Outlet runs a catalog business. It sells only one type of
coffee beans, harvested exclusively in the remote area of Irian Java. The company sells
the coffee in 2-lb bags only, and the price of a single 2-lb bag is $5.50. When a customer
places an order, the company ships the order in boxes. The boxes come in three sizes: the
large box holds twenty 2-lb bags, the medium 10 bags, and the small 5 bags. The cost of
a large box is $1.80; a medium box, $1.00; and a small box, $0.60. The order is shipped
in the least expensive manner. For example, the order of 52 bags will be shipped in four
boxes, two large, one medium, and one small. The rule for packaging is to fill the large
and medium boxes completely, i.e., the box is fully packed. Only the small boxes can
have empty spaces. For example, to ship 52 bags, you could use 3 large boxes but that
would leave the third box not fully packed. Develop an application that computes the
total cost of an order. Display the output in the following format:

See Exercise3_29.java.

30. Repeat Exercise 29, but this time, accept the date when the order is placed
and display the expected date of arrival. The expected date of arrival is two weeks (14
days) from the date of order. The order date is entered as a single string in the
MM/dd/yyyy format. For example, November 1, 2010 is entered as 11/01/2010. There
will be exactly two digits each for the month and day and four digits for the year.
Display the output in the following format:
See Exercise3_30.java.

31. Using a Turtle object from the galapagos package, draw three
rectangles. Accept the width and the length of the smallest rectangle from the user. The
middle and the largest rectangles are 40 and 80 percent larger, respectively, than the
smallest rectangle. The galapagos package and its documentation are available at the
McGraw-Hill book website.

See Exercise3_31.java.

32. Develop a program that draws a bar chart using a Turtle object. Input
five int values, and draw the vertical bars that represent the entered values in the
following manner:

Your Turtle must draw everything shown in the diagram, including the axes and
numbers.

See Exercise3_28.java.

You might also like