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.


2.7 Fill in the blanks in each of the following:
  1. __________ are used to document a program and improve its readability.
  2. An input dialog capable of receiving input from the user is displayed with method ___________ of class ______________.
  3. A Java statement that makes a decision is _____________.
  4. Calculations are normally performed by ________________ statements.
  5. An input dialog capable of receiving input from the user is displayed with method _____________ of class _______________.

2.8 Write Java statements that accomplish each of the following:

  1. Display the message "Enter two numbers" using class JOptionPane.
  2. Assign the product of variables b and c to variable a.
  3. State that a program performs a sample payroll calculation (i.e., use text that helps to document a program).

2.9 State which of the following are true and which are false. If false, explain why.

  1. Java operators are evaluated from left to right.
  2. The following are all valid variable names: _under_bar_, m928134, t5, j7, her_sales$, his_$account_total, a, b$, c, z, z2.
  3. A valid Java arithmetic expression with no parentheses is evaluated from left to right.
  4. The following are all invalid variable names: 3g, 87, 67h2, h22, 2h.

2.10 Fill in the blanks in each of the following:

  1. What arithmetic operations are on the same level of precedence as multiplication?
    __________________.
  2. When parentheses are nested, which set of parentheses is evaluated first in an arithmetic expression? ___________________.
  3. A location in the computer's memory that may contain different values at various times throughout the execution of a program is called a _______________.

2.11 What displays in the message dialog when each of the following Java statements is performed? Assume x = 2 and y = 3.

  1. JOptionPane.showMessageDialog( null, "x = " + x );
  2. JOptionPane.showMessageDialog( null,
    "The value of x + x is " + ( x + x ) );
  3. JOptionPane.showMessageDialog( null, "x =" );
  4. JOptionPane.showMessageDialog(null,
    ( x + y ) + " = " + ( y + x ) );

2.12 Which of the following Java statements contain variables whose values are destroyed (i.e., changed or replaced)?

  1. p = i + j + k + 7;
  2. JOptionPane.showMessageDialog( null,
    "variables whose values are destroyed" );
  3. JOptionPane.showMessageDialog( null, "a = 5" );
  4. stringVal = JOptionPane.showInputDialog( "Enter string: );

2.13 Given y = ax3 + 7, which of the following are correct statements for this equation?

  1. y = a * x * x * x + 7;
  2. y = a * x * x * (x + 7);
  3. y = (a * x) * x * (x + 7);
  4. y = (a * x) * x * x + 7;
  5. y = a * (x * x * x) + 7;
  6. y = a * x * (x * x + 7);

2.14 State the order of evaluation of the operators in each of the following Java statements and show the value of x after each statement is performed.

  1. x = 7 + 3 * 6 / 2 - 1;
  2. x = 2 % 2 + 2 * 2 - 2 / 2;
  3. x = ( 3 * 9 * ( 3 + ( 9 * 3 / ( 3 ) ) ) );

2.15 Write an application that displays the numbers 1 to 4 on the same line with each pair of adjacent numbers separated by one space. Write the program using the following methods.

  1. Using one System.out statement.
  2. Using four System.out statements.

2.16 Write an application that asks the user to enter two numbers, obtains the two numbers from the user and prints the sum, product, difference and quotient of the two numbers. Use the techniques shown in Fig. 2.8.

2.17 Write an application that asks the user to enter two integers, obtains the numbers from the user and displays the larger number followed by the words "is larger" in an information message dialog. If the numbers are equal, print the message "These numbers are equal." Use the techniques shown in Fig. 2.17.

2.18 Write an application that inputs three integers from the user and displays the sum, average, product, smallest and largest of these numbers in an information message dialog. Use the GUI techniques shown in Fig. 2.17. Note: The average calculation in this exercise should result in an integer representation of the average. So, if the sum of the values is 7, the average will be 2 not 2.3333...

2.19 Write an application that inputs from the user the radius of a circle and prints the circle’s diameter, circumference and area. Use the constant value 3.14159 for p. Use the GUI techniques shown in Fig. 2.8. [Note: You may also use the predefined constant Math.PI for the value of p. This constant is more precise than the value 3.14159. Class Math is defined in the java.lang package, so you do not need to import it.] Use the following formulas (r is the radius): diameter = 2r, circumference = 2pr, area = pr2.

2.20 Write an application that displays in the command window a box, an oval, an arrow and a diamond using asterisks (*) as follows:
*********          ***              *              *
*       *        *     *           ***            * *
*       *       *       *         *****          *   *
*       *       *       *           *           *     *
*       *       *       *           *          *       *
*       *       *       *           *           *     *
*       *       *       *           *            *   *
*       *        *     *            *             * *
*********          ***              *              *
 

2.21 Modify the program you created in Exercise 2.20 to display the shapes in a JOptionPane.PLAIN_MESSAGE dialog. Does the program display the shapes exactly as in Exercise 2.20?

2.22 What does the following code print?

System.out.println( "*\n**\n***\n****\n*****" );

2.23 What does the following code print?

System.out.println( "*" );
System.out.println( "***" );
System.out.println( "*****" );
System.out.println( "****" );
System.out.println( "**" );

2.24 What does the following code print?

System.out.print( "*" );
System.out.print( "***" );
System.out.print( "*****" );
System.out.print( "****" );
System.out.println( "**" );

2.25 What does the following code print?

System.out.print( "*" );
System.out.println( "***" );
System.out.println( "*****" );
System.out.print( "****" );
System.out.println( "**" );

2.26 Write an application that reads five integers and determines and prints the largest and the smallest integers in the group. Use only the programming techniques you learned in this chapter.

2.27 Write an application that reads an integer and determines and prints whether it is odd or even. (Hint: Use the modulus operator. An even number is a multiple of two. Any multiple of two leaves a remainder of zero when divided by 2.)

2.28 Write an application that reads in two integers and determines and prints if the first is a multiple of the second. (Hint: Use the modulus operator.)

2.29 Write an application that displays in the command window a checkerboard pattern as follows:
* * * * * * * *
 * * * * * * * *
* * * * * * * *
 * * * * * * * *
* * * * * * * *
 * * * * * * * *
* * * * * * * *
 * * * * * * * *
 

2.30 Modify the program you wrote in Exercise 2.29 to display the checkerboard pattern in a JOptionPane.PLAIN_MESSAGE dialog. Does the program display the shapes exactly as in Exercise 2.29?

2.31 Here's a peek ahead. In this chapter you learned about integers and the data type int. Java can also represent uppercase letters, lowercase letters and a considerable variety of special symbols. Every character has a corresponding integer representation. The set of characters a computer uses and the corresponding integer representations for those characters is called that computer’s character set. You can indicate a character value in a program by simply enclosing that character in single quotes as with 'A'.

You can determine the integer equivalent of a character by preceding that character with (int)this is called a cast (we will say more about casts in Chapter 4).

(int) 'A'

The following statement would output a character and its integer equivalent

System.out.println(
"The character " + 'A' + " has the value " + (int) 'A' );

When the preceding statement executes, it displays the character A and the value 65 (from the so- called Unicode character set) as part of the string.

Write an application that displays the integer equivalents of some uppercase letters, lowercase letters, digits and special symbols. At a minimum, display the integer equivalents of the following: A B C a b c 0 1 2 $ * + / and the blank character.

2.32 Write an application that inputs one number consisting of five-digits from the user, separates the number into its individual digits and prints the digits separated from one another by three spaces each. For example, if the user types in the number 42339, the program should print
 
4 2 3 3 9

Hint: This exercise is possible with the techniques you learned in this chapter. You will need to use both division and modulus operations to "pick off" each digit.

For the purpose of this exercise assume that the user enters the correct number of digits. What happens when you execute the program and type a number with more than five digits? What happens when you execute the program and type a number with fewer than five digits?

2.33 Using only the programming techniques you learned in this chapter, write an application that calculates the squares and cubes of the numbers from 0 to 10 and prints the resulting values in table format as follows:
number square cube
0 0 0
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
 Note: This program does not require any input from the user.

2.34 Write a program that reads a first name and a last name from the user as two separate inputs and concatenates the first name and last name separated by a space. Display in a message dialog the concatenated name.

2.35 Write a program that inputs five numbers and determines and prints the number of negative numbers input, number of positive numbers input and the number of zeros input.


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.


2.7 Fill in the blanks in each of the following:
  1. Are used to document a program and improve its readability.
    ANS: Comments
  2. An input dialog capable of receiving input from the user is displayed with method of class .
    ANS: showInputDialog, JOptionPane.
  3. A Java statement that makes a decision is .
    ANS: if.
  4. Calculations are normally performed by statements.
    ANS: assignment
  5. An input dialog capable of receiving input from the user is displayed with method of class .
    ANS: showMessageDialog, JOptionPane.

2.9 State which of the following are true and which are false. If false, explain why.

  1. Java operators are evaluated from left to right.
    ANS: False. Some operators (e.g., assignment, =) evaluate from right to left.
  2. The following are all valid variable names: _under_bar_, m928134, t5, j7, her_sales$, his_$account_total, a, b$, c, z, z2.
    ANS: True.
  3. A valid Java arithmetic expression with no parentheses is evaluated from left to right.
    ANS: False. The expression is evaluated according to operator precedence.
  4. The following are all invalid variable names: 3g, 87, 67h2, h22, 2h.
    ANS: False. Identifier h22 is a valid variable name.

2.11 What displays in the message dialog when each of the following Java statements is performed? Assume x = 2 and y = 3.

  1. JOptionPane.showMessageDialog( null, "x = " + x );
    ANS: x = 2
  2. JOptionPane.showMessageDialog
    ( null,"The value of x + x is " + ( x + x ) );

    ANS: The value of x + x is 4
  3. JOptionPane.showMessageDialog( null, "x =" );
    ANS: x =
  4. JOptionPane.showMessageDialog(null,
    ( x + y ) + " = " + ( y + x ) );

    ANS: 5 = 5

2.17

// Exercise 2.17 Solution
// Larger.java
// Program determines the larger of two numbers
import javax.swing.JOptionPane;

public class Larger {
   public static void main( String args[] )
   {
      String firstNumber,    // first string entered by user
             secondNumber,   // second string entered by user
             result;         // a string containing the output
       int number1,          // first number to compare
           number2;          // second number to compare

       // read first number from user as a string
       firstNumber =
          JOptionPane.showInputDialog( "Enter first integer:" );

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

       // convert numbers from type String to type int
       number1 = Integer.parseInt( firstNumber );
       number2 = Integer.parseInt( secondNumber );

       if ( number1 > number2 )
          result = number1 + " is larger.";
       else if ( number1 < number2 )
          result = number2 + " is larger.";
       else
          result = "These numbers are equal."; 

       // Display results
       JOptionPane.showMessageDialog(
          null, result, "Comparison Results",
          JOptionPane.INFORMATION_MESSAGE );

       System.exit( 0 );
   }  
}

2.19

// Exercise 2.19 Solution
// Circle.java
// Program calculate the area, circumference, and diameter for a circle
import javax.swing.JOptionPane;

public class Circle { 
   public static void main( String args[] )
   {
      String input,       // string entered by user
             result;      // output display string
      int radius;         // radius of circle

      // read from user as a string
      input =
         JOptionPane.showInputDialog( "Enter radius:" );

      // convert number from type String to type int
      radius = Integer.parseInt( input );

     result = "Diameter is " + ( 2 * radius ) + 
              "\nArea is " + ( Math.PI * radius * radius ) +
              "\nCircumference is " + ( 2 * Math.PI * radius );

     // Display results
     JOptionPane.showMessageDialog(
        null, result, "Calculation Results",
        JOptionPane.INFORMATION_MESSAGE );

     System.exit( 0 );
   }
}

2.24 What does the following code print?

System.out.print( "*" );
System.out.print( "***" );
System.out.print( "*****" );
System.out.print( "****" );
System.out.println( "**" );

ANS: ***************

2.27

// Exercise 2.27 Solution
// OddEven.java
// Program determines if a number is odd or even
import javax.swing.JOptionPane;

public class OddEven {
   public static void main( String args[] )
   {
      String input,       // string entered by user
             result;      // output display string
      int number;         // number

      // read from user as a string
      input =
         JOptionPane.showInputDialog( "Enter integer:" );

      // convert number from type String to type int
      number = Integer.parseInt( input );

      if ( number % 2 == 0 )
         result = "Number is even.";
      else
         result = "Number is odd.";
     
      // Display results
      JOptionPane.showMessageDialog(
         null, result, "Calculation Results",
         JOptionPane.INFORMATION_MESSAGE );

      System.exit( 0 );
   }
}

2.29

// Exercise 2.29 Solution
// Checker.java
// Program draws a checkerboard

public class Checker {
   public static void main( String args[] )
   {
      System.out.println( "* * * * * * * *" );
      System.out.println( " * * * * * * * *" );
      System.out.println( "* * * * * * * *" );
      System.out.println( " * * * * * * * *" );
      System.out.println( "* * * * * * * *" );
      System.out.println( " * * * * * * * *" );
      System.out.println( "* * * * * * * *" );
      System.out.println( " * * * * * * * *" );
   }
}

2.31

// Exercise 2.31 Solution
// Display.java
// Program prints a unicode character
// and its integer equivalent

public class Display {
   public static void main( String args[] )
   {
      System.out.println( "The character " + 'A' +
                    " has the value " + ( int ) 'A' );
      System.out.println( "The character " + 'B' +
                    " has the value " + ( int ) 'B' );
      System.out.println( "The character " + 'C' +
                    " has the value " + ( int ) 'C' );
      System.out.println( "The character " + 'a' +
                    " has the value " + ( int ) 'a' );
      System.out.println( "The character " + 'b' +
                    " has the value " + ( int ) 'b' );
      System.out.println( "The character " + 'c' +
                    " has the value " + ( int ) 'c' );
      System.out.println( "The character " + '0' +
                    " has the value " + ( int ) '0' );
      System.out.println( "The character " + '1' +
                    " has the value " + ( int ) '1' );
      System.out.println( "The character " + '2' +
                    " has the value " + ( int ) '2' );
      System.out.println( "The character " + '$' +
                    " has the value " + ( int ) '$' );
      System.out.println( "The character " + '*' +
                    " has the value " + ( int ) '*' );
      System.out.println( "The character " + '/' +
                    " has the value " + ( int ) '/' );
      System.out.println( "The character " + ' ' +
                    " has the value " + ( int ) ' ' );
      System.out.println( "The character " + ',' +
                    " has the value " + ( int ) ',' );
   }
}