Programming Exercises

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.

created 08/01/99


Chapter 11 Programming Exercises

Exercise 1

Write a program that calculates the annual cost of running an appliance. The program will ask the user for the cost per kilowatt-hour and the number of kilowatt-hours the appliance uses in a year:

Enter cost per kilowatt-hour  in cents
8.42
Enter kilowatt-hours used per year
653
Annual cost: 54.9826
Click here to go back to the main menu.

Exercise 2

When a brick is dropped from a tower, it falls faster and faster until it hits the earth. The distance it travels is given by

d = (1/2)gt2

Here d is in feet, t is the time in seconds, and g is 32.174. Write a program that asks the user for the number of seconds and then prints out the speed.

Enter the number of seconds: 5.4
Speed of the brick: 469.092 feet per second

Use the program to determine how lonk it would take a brick to fall 100 feet.

Click here to go back to the main menu.

Exercise 3

The base 2 logarithm of a number is defined by:

log2 X = n  if 2n = X

For example

log2 32 = 5,  because  25 = 32  
log2 1024 = 10,  because 210 = 1024 

Write a program that inputs a number and outputs its base 2 logarithm. Use floating point input. This problem would be easy, but the Math package does not have a base 2 logarithm method. Instead you have to do this:

log2 X = (loge X) / (loge 2)

Here, loge X is the natural logarithm of X. Use this function in the Java Math package:

Math.log( X )

When you use this, X must be a double. Write the program so that the user can enter floating point numbers.

Enter a double:
998.65
Base 2 log of 998.65 is 9.963835330516641
Click here to go back to the main menu.

Exercise 4

The harmonic mean of two numbers is given by:

H = 2 / ( 1/X + 1/Y )

This is sometimes more useful than the more usual average of two numbers. Write a program that inputs two numbers (as floating point) and writes out both the usual average (the arithmetic mean) and the harmonic mean.

Enter X:
12
Enter Y:
16
Arithmetic mean: 14.0
Harmonic   mean: 13.714285714285715
Click here to go back to the main menu.