Exercises

Included below are short-answer and programming exercises. Answers are provided for those exercises whose exercise number is a hyperlink. Because college faculty use these exercises in their exams, we have provided answers to roughly half of the exercises included here.


4.9 Identify and correct the errors in each of the following. [Note: There may be more than one error in each piece of code.]

  1. if ( age >= 65 );
    System.out.println( "Age greater than or equal to 65" );


    else

    System.out.println( "Age is less than 65 )";
  2. int x = 1, total;
    while ( x <= 10 ) {
    total += x;
    ++x;


    }

  3. While ( x <= 100 )
    total += x;
    ++x;
  4. while ( y > 0 ) {
    System.out.println( y );
    ++y;

4.10 What does the following program print?

public class Mystery {

public static void main( String args[] )
{
int y, x = 1, total = 0;
while ( x <= 10 ) {
y = x * x;
System.out.println( y );
total += y;
++x;

}
System.out.println( "Total is " + total );

}

}

For Exercises 4.11 through 4.14, perform each of these steps:

  1. Read the problem statement.
  2. Formulate the algorithm using pseudocode and top-down, stepwise refinement.
  3. Write a Java program.
  4. Test, debug and execute the Java program.
  5. Process three complete sets of data.

4.11 Drivers are concerned with the mileage obtained by their automobiles. One driver has kept track of several tankfuls of gasoline by recording miles driven and gallons used for each tankful. Develop a Java application that will input the miles driven and gallons used (both as integers) for each tankful. The program should calculate and display the miles per gallon obtained for each tankful and print the combined miles per gallon obtained for all tankfuls up to this point. All average calculations should produce floating-point results. Use input dialogs to obtain the data from the user.

4.12 Develop a Java application that will determine if a department store customer has exceeded the credit limit on a charge account. For each customer, the following facts are available:

  1. Account number
  2. Balance at the beginning of the month
  3. Total of all items charged by this customer this month
  4. Total of all credits applied to this customer's account this month
  5. Allowed credit limit

The program should input each of these facts from input dialogs as integers, calculate the new balance (= beginning balance + charges ? credits), display the new balance and determine if the new balance exceeds the customer's credit limit. For those customers whose credit limit is exceeded, the program should display the message, "Credit limit exceeded."

 

4.13 A large company pays its salespeople on a commission basis. The salespeople receive $200 per week plus 9% of their gross sales for that week. For example, a salesperson who sells $5000 worth of merchandise in a week receives $200 plus 9% of $5000, or a total of $650. You have been supplied with a list of items sold by each salesperson. The values of these items are as follows:

Develop a Java application that inputs one salesperson's items sold for last week and calculates and displays that salesperson's earnings. There is no limit to the number of items sold by a salesperson.

4.14 Develop a Java application that will determine the gross pay for each of three employees. The company pays "straight-time" for the first 40 hours worked by each employee and pays "time-and-a- half" for all hours worked in excess of 40 hours. You are given a list of the employees of the company, the number of hours each employee worked last week and the hourly rate of each employee. Your program should input this information for each employee, and should determine and display the employee's gross pay. Use input dialogs to input the data.

4.15 The process of finding the largest value (i.e., the maximum of a group of values) is used frequently in computer applications. For example, a program that determines the winner of a sales contest would input the number of units sold by each salesperson. The salesperson who sells the most units wins the contest. Write a pseudocode program and then a Java application that inputs a series of 10 single-digit numbers as characters, and determines and prints the largest of the numbers. [Hint: Your program should use three variables as follows:

4.16 Write a Java application that utilizes looping to print the following table of values:

 

4.17 Using an approach similar to Exercise 4.15, find the two largest values of the 10 digits entered. (Note: You may input each number only once.)

4.18 Modify the program in Fig. 4.11 to validate its inputs. On any input, if the value entered is other than 1 or 2, keep looping until the user enters a correct value.

4.19 What does the following program print?

public class Mystery2 {

public static void main( String args[] )
{
int count = 1;
while ( count <= 10 ) {
System.out.println( count % 2 == 1 ?
"****" : "++++++++" );
++count;

}

}

}

4.20 What does the following program print?

public class Mystery3 {

public static void main( String args[] )
{
int row = 10, column;
while ( row >= 1 ) {
column = 1;
while ( column <= 10 ) {
System.out.print( row % 2 == 1 ? "<" : ">" );
++column;

}

--row;
System.out.println();

}

}

}

4.21 (Dangling-Else Problem) Determine the output for each of the following when x is 9 and y is 11 and when x is 11 and y is 9. Note that the compiler ignores the indentation in a Java program. Also, the Java compiler always associates an else with the previous if unless told to do otherwise by the placement of braces ({}). Because, on first glance, the programmer may not be sure which if an else matches, this is referred to as the "dangling-else" problem. We have eliminated the indentation from the following code to make the problem more challenging. (Hint: Apply indentation conventions you have learned.)

  1. if ( x < 10 )
    if ( y > 10 )
    System.out.println( "*****" );
    else
    System.out.println( "#####" );
    System.out.println( "$$$$$" );
  2. if ( x < 10 ) {
    if ( y > 10 )
    System.out.println( "*****" );
    }
    else {
    System.out.println( "#####" );
    System.out.println( "$$$$$" );
    }

4.22 (Another Dangling-Else Problem) Modify the following code to produce the output shown. Use proper indentation techniques. You may not make any changes other than inserting braces and changing the indentation of the code. The compiler ignores indentation in a Java program. We have eliminated the indentation from the following code to make the problem more challenging. [Note: It is possible that no modification is necessary.]

if ( y == 8 )
if ( x == 5 )
System.out.println( "@@@@@" );
else
System.out.println( "#####" );
System.out.println( "$$$$$" );
System.out.println( "&&&&&" );

  1. Assuming x = 5 and y = 8, the following output is produced.
  1. Assuming x = 5 and y = 8, the following output is produced.
  1. Assuming x = 5 and y = 8, the following output is produced.
  1. Assuming x = 5 and y = 7, the following output is produced. [Note: The last three output statements after the else are all part of a compound statement.]

 

4.23 Write an applet that reads in the size of the side of a square and displays a hollow square of that size out of asterisks using the drawString method inside your applet?s paint method. Use an input dialog to read the size from the user. Your program should work for squares of all side sizes between 1 and 20.

4.24 A palindrome is a number or a text phrase that reads the same backward as forward. For example, each of the following five-digit integers are palindromes: 12321, 55555, 45554 and 11611. Write an application that reads in a five-digit integer and determines whether or not it is a palindrome. If the number is not five digits, display an error message dialog indicating the problem to the user. When the user dismisses the error dialog, allow the user to enter a new value.

4.25 Write an application that inputs an integer containing only 0s and 1s (i.e., a "binary" integer) and print its decimal equivalent. (Hint: Use the modulus and division operators to pick off the "binary" number?s digits one at a time from right to left. Just as in the decimal number system where the rightmost digit has a positional value of 1 and the next digit left has a positional value of 10, then 100, then 1000, etc., in the binary number system the rightmost digit has a positional value of 1, the next digit left has a positional value of 2, then 4, then 8, etc. Thus the decimal number 234 can be interpreted as 4 * 1 + 3 * 10 + 2 * 100. The decimal equivalent of binary 1101 is 1 * 1 + 0 * 2 + 1 * 4 + 1 * 8 or 1 + 0 + 4 + 8 or 13.)

4.26 Write an application that displays the following checkerboard pattern:

 

Your program may use only three output statements, one of the form

System.out.print( "* " );

one of the form

System.out.print( " " );

and one of the form

System.out.println();

Note that the preceding statement indicates that the program should output a single newline character to drop to the next line on the output. (Hint: Repetition structures are required in this exercise.)

4.27 Write an application that keeps displaying in the command window the multiples of the integer 2, namely 2, 4, 8, 16, 32, 64, etc. Your loop should not terminate (i.e., you should create an infinite loop). What happens when you run this program?

4.28 What's wrong with the following statement? Provide the correct statement to add one to the sum of x and y.

System.out.println( ++(x + y) );

4.29 Write an application that reads three nonzero values entered by the user in input dialogs and determines and prints if they could represent the sides of a triangle.

4.30 Write an application that reads three nonzero integers and determines and prints if they could be the sides of a right triangle.

4.31 A company wants to transmit data over the telephone, but they are concerned that their phones may be tapped. All of their data is transmitted as four-digit integers. They have asked you to write a program that will encrypt their data so that it may be transmitted more securely. Your application should read a four-digit integer entered by the user in an input dialog and encrypt it as follows: Replace each digit by (the sum of that digit plus 7) modulus 10. Then swap the first digit with the third, and swap the second digit with the fourth. Then print the encrypted integer. Write a separate application that inputs an encrypted four-digit integer and decrypts it to form the original number.

4.32 The factorial of a nonnegative integer n is written n! (pronounced "n factorial") and is defined as follows:

n! = n · (n - 1) · (n - 2) · ...· 1 (for values of n greater than or equal to 1)

and

n! = 1 (for n = 0).

For example, 5! = 5 · 4 · 3 · 2· 1, which is 120.

  1. Write an application that reads a nonnegative integer from an input dialog and computes and prints its factorial.
  2. Write an application that estimates the value of the mathematical constant e by using the formula
  1. Write an application that computes the value of ex by using the formula:


Selected Answers

Included below are answers to approximately half the of the exercises in the Cyber Classroom. We are not able to include answers to every exercise because college faculty use these exercises in their classroom exams.


4.9 Identify and correct the errors in each of the following. [Note: There may be more than one error in each piece of code.]

  1. if ( age >= 65 );

    System.out.println( "Age greater than or equal to 65" );


    else

    System.out.println( "Age is less than 65 )";


    ANS: Semicolon at the end of the if condition should be removed. The closing double quote of the second System.out.println should be inside of the closing parenthesis.

  2. int x = 1, total;
    while ( x <= 10 ) {

    total += x;
    ++x;


    }


    ANS: The variable total should be initialized to zero.

  3. While ( x <= 100 )

    total += x;
    ++x;


    ANS: The W in While should be lowercase. The two statements should be enclosed in curly braces to properly group them into the body of the while; otherwise the loop will be an infinite loop.

  4. while ( y > 0 ) {

    System.out.println( y );
    ++y;


    ANS: The ++ operator should be changed to --. The closing curly brace for the while loop is missing.

4.11

	
// Exercise 4.11 Solution
// Gas.java
// Program calculates average mpg
import javax.swing.JOptionPane;

public class Gas {
   public static void main( String args[] )
   {
      int miles, gallons;
      int totalMiles = 0, totalGallons = 0;
      float milesPerGallon;
      float totalMilesPerGallon;
      String input1, input2, result = "";

      while( true ) {
         // read first number from user as a string
         input1 =
            JOptionPane.showInputDialog( "Enter miles:" );

         // read second number from user as a string
         input2 =
            JOptionPane.showInputDialog( "Enter gallons:" );          

         // convert numbers from type String to type int
         miles = Integer.parseInt( input1 );
         gallons = Integer.parseInt( input2 );

         totalMiles += miles;
         totalGallons += gallons ;
      
         if ( gallons != 0 ) {
            milesPerGallon = ( float ) miles / gallons;
            result = "MPG this tankful: " + milesPerGallon + "\n";
         }
         else { System.exit( 0 ); }
         
         if ( totalGallons != 0 ) {       // never will be 0 due to test above
            totalMilesPerGallon = ( float ) totalMiles / totalGallons;
            result += "\nTotal MPG: " + totalMilesPerGallon;
         }
   
         JOptionPane.showMessageDialog(
            null, result, "Milage",
            JOptionPane.INFORMATION_MESSAGE );
      }
   }
}

4.13

	
// Exercise 4.13 Solution
// Sales.java
// Program calculates sales
import javax.swing.JOptionPane;

public class Sales {
   public static void main( String args[] )
   {
      double gross = 0.0, earnings;
      int product = 0, number;
      String input;

      while ( product < 4 ) {
         product++;
         // read number from user as a string
         input =
            JOptionPane.showInputDialog( 
               "Enter number sold of product #" + product + ":" );
               
         // convert numbers from type String to type int
         number = Integer.parseInt( input );

         if ( product == 1 )
            gross = gross + number * 239.99;
         else if ( product == 2 )
            gross = gross + number * 129.75;
         else if ( product == 3 )
            gross = gross + number * 99.95;
         else if ( product == 4 )
            gross = gross + number * 350.89;
          }     
      earnings = 0.09 * gross + 200;

      String result = "Earnings this week: " + earnings;

      JOptionPane.showMessageDialog(
            null, result, "Sales",
            JOptionPane.INFORMATION_MESSAGE );
      System.exit( 0 );
   }
}

4.16

	
// Exercise 4.16 Solution
// Table.java
// Program prints a table of values

public class Table {
   public static void main( String args[] )
   {
      int n = 0;

      System.out.println( "N\t10*N\t100*N\t1000*N\n" );

      while ( ++n <= 5 ) 
         System.out.println( n + "\t" + ( 10 * n ) +
                             "\t" + ( 100 * n ) + "\t"
                             + ( 1000 * n ) );
   }
}

4.18

	
// Exercise 4.18 Solution
// Analysis.java
// Analysis of examination results
import javax.swing.JOptionPane;

public class Analysis {

   public static void main( String args[] )
   {
      // initializing variables in declarations
      int passes = 0, failures = 0, student = 1, result;
      String input, output;

      // process 10 students; counter-controlled loop
      while ( student <= 10 ) {
         input = JOptionPane.showInputDialog(
            "Enter result (1=pass,2=fail): " );

         result = Integer.parseInt( input );
           
         if ( result == 1 ) {     // if/else nested in while
            passes = passes + 1;
            student = student + 1;
         }
         else if ( result == 2 ) {
            failures = failures + 1;
            student = student + 1;
         }
         else
            JOptionPane.showMessageDialog(
            null, "Invalid Input", "Error",
            JOptionPane.ERROR_MESSAGE );
      }
   
      output = "Passed " + passes;
      output += "\nFailed " + failures;
   
      if ( passes > 8 )
         output += "\nRaise tuition ";

      JOptionPane.showMessageDialog(
            null, output, "Results",
            JOptionPane.INFORMATION_MESSAGE );

      System.exit( 0 );
   }
}

4.23

	
// Exercise 4.23 Solution
// Hollow.java
// Program prints a hollow square
import javax.swing.*;
import java.awt.Graphics;

public class Hollow extends JApplet {
   int stars;

   public void init()
   {
      String input;          // for user input
      stars = 0;
      // read number from user as a string
      input =
         JOptionPane.showInputDialog(
            "Enter length of side:" );
               
      // convert numbers from type String to type int
      stars = Integer.parseInt( input );
      
      if ( stars < 1 ) {
         stars = 1;
          JOptionPane.showMessageDialog(
            null, "Using default value 1", "Error",
            JOptionPane.ERROR_MESSAGE );
      }
      else if ( stars > 20 ) {
         stars = 20;
         JOptionPane.showMessageDialog(
            null, "Using default value 20", "Error",
            JOptionPane.ERROR_MESSAGE );
      }
   }

   public void paint( Graphics g )
   {
      int x = 5, y = 70;
      int i = 1, j = 1;

      while ( i <= stars ) {        
         
         while ( j <= stars ) {
            if ( i == 1 )
               g.drawString( "*", x += 5, y );
            else if ( i == stars )
               g.drawString( "*", x += 5, y );
            else if ( j == 1 )
               g.drawString( "*", x += 5, y );
            else if ( j == stars )
                g.drawString( "*", x += 5, y );
            else
               g.drawString( " ", x += 5, y );

            j++; 
         }

         j = 1;
         i++;           
         y += 5;
         x = 5;           
      }      
   }
}

4.26

	
// Exercise 4.26 Solution
// Stars.java
// Program prints a checkerboard pattern

public class Stars {

   public static void main( String args[] )
   {
      int row = 0;

      while ( ++row <= 8 ) {
         int col = 0;

         if ( row % 2 == 0 )
            System.out.print( " " );

         while ( ++col <= 8 ) 
            System.out.print( "* " );

         System.out.println();
      }
   }
}

4.27

	
// Exercise 4.27 Solution
// Infinite.java
// Program creates an infinite loop
// Runs out of integers (number is too big)

public class Infinite {
   
   public static void main( String args[] )
   {
      int x = 1;
      while ( true ) {
         x *= 2;
         System.out.println( x + " " );
      }
   }
}

4.30

	
// Execise 4.30 Solution
// Triangle2.java
// Program takes three integers and
// determines if they form the sides
// of a right triangle
import javax.swing.JOptionPane;

public class Triangle2 {
   public static void main( String args[] )
   {
       int side1, side2, hypotenuse;
       String input, result;

      // read number from user as a string
      input = JOptionPane.showInputDialog(
            "Enter length of side 1:" );
               
      side1 = Integer.parseInt( input );

      // read number from user as a string
      input =
         JOptionPane.showInputDialog(
            "Enter length of side 2:" );

      side2 = Integer.parseInt( input );

      // read number from user as a string
      input =
         JOptionPane.showInputDialog(
            "Enter length of hypotenuse:" );

      hypotenuse = Integer.parseInt( input );
      
      if ( ( side1 * side1 + side2 * side2 ) == ( hypotenuse * hypotenuse ) )
         result = "These are the sides of a right triangle.";
      else
         result = "These do not form a right triangle.";   
      
      JOptionPane.showMessageDialog(
            null, result, "Result",
            JOptionPane.INFORMATION_MESSAGE );

      System.exit( 0 );
   }
}