CS 120 Exam 2 Key

Tom Linton, April 15, 1999

In the grey box below,
predict your score.
All accurate predictions
will be rewarded!
Problem
Number
Possible
Points
Your
Score
1 25  
2
28
 
3
22
 
 
4
25
 
Total
100
 

These are shortcut links to the individual questions:
Number 1: Short Answer
Number 2: Code Interpretation
Number 3: Code Writing
Number 4: Code Interpretation

The answers appear in colored fonts most of the time.
 

  1. Short Answer-25 points total:
    1. (5 points) The code fragment below increases the value of the (assumed to be of type int) variable count by one. Give two other code fragments which accomplish the same thing.

    2.  

       

      count = count + 1;   count += 1;    count++;
       

    3. (5 points) What happens when you mix decimal values (type double) with integer values (type int) in simple arithmetical expressions like x + N; 2.0 * 5; or 3.2 / 5 + 4;?

    4. Mixing ints and doubles in an arithmetic operation causes the int value to be cast as a double, yielding a double result.
       

    5. (10 points) A user defined class called Player has a private int data field named bankRoll. Write a method named getBankRoll, of the Player class, which returns the current value of this data field. Then write a method called setBankRoll, which sets the value of bankRoll equal to the one input parameter for this method. Be sure to give the header-declaration line of each method.

    6. getBankRoll is an accessor method, setBankRoll a modifier method. These are nearly always one-liners:

      public int getBankRoll() {
          return bankRoll;
      }

      public void setBankRoll(int newValue) {
          bankRoll = newValue;
      }


     
    1. (5 points) The output from the code fragment:

    2.    int num = 5;
         int num2 = num++ + 3;
         System.out.println("num = " + num + ", num2 = " + num2 + ".");
      is:    num = 6, num2 = 8.

      Explain why this is so. In particular, 6 + 3 = 9 not 8, so what's up?

      The second line accomplishes four things, more or less in this order (the fact that the increment to num is done last, is all that really matters): A memory location for an int variable num2 is set aside; then the value (num + 3) = 8 is calculated; then 8 is assigned to num2; and finally num is incremented (to 6).

  1. (code interpretation-28 points)
    1. (12 points) What is the value of num after each line of the following code fragment is executed? That is, assume the entire fragment is executed at once, and give a line-by-line analysis of the value of num after each line is executed.

    2.    int num = 25;  num = 25
         num += 5;      num = 25 + 5 = 30
         num /= 4;      num = 30 / 4 = 7
         num--;        num = num - 1 = 6
       
    3. (16 points) Explain what the following method does and how it works (this is an incredibly useful technique which you should remember!). Assume this method definition appears in a class which extends the SimpleGUI class.

    4.  

       

      public int getIntLowerOnly(String promptString, int lower) {
         int userInput;
         do {
            userInput = getInt(promptString);
            if (userInput < lower)
               displayResult("Your input is less than " + lower +
                  ". Please try again.");
         } while (userInput < lower);
         return userInput;
      }

      The method repeatedly prompts the user (using the 1st argument as a text prompt) for an integer, unitl the user enters a value bigger than or equal to the second argument (lower). If the user enters a value which is too small, an error message is displayed and the loop body is repeated. This is accomplished using a do-while loop, since in all cases, we must ask the user for a value at least one time. A typical call might be:

      getIntLower("Give positive integer: ", 1);
  2. (code writing-22 points)
    1. (5 points) In Java, how do you say "if N is negative or N is even, add 5 to N, otherwise decrease N by 1"?

    2.  

       

      if ( (N < 0) || ( (N % 2) == 0) )
          N += 5;
      else
          N--;
       

    3. (7 points) Write a switch statement, where the switch variable is N. For N = 1,2,3,4 or 5, your statement should "return" a String equivalent of the ordinal version of N, namely 1st, 2nd, 3rd, 4th or 5th respectively. For all other values of N, your statement should "return" an error message String, like "Your input is out of range.". Recall that "return" and "break", force an exit from a switch block.

    4.  

       

      switch(N) {
          case 1: return "1st";
          case 2: return "2nd";
          case 3: return "3rd";
          case 4: return "4th";
          case 5: return "5th";
          default: return "Your input is out of range.";
      }
       

    5. (10 points) At the end of a method with return type void, so the output is just displayed, not returned (in a class extending the SimpleGUI class), you need to print a String which indicates the number of nickels used (in your computation of "the answer"). The data field (of type int) named numberOfNickels contains the numeric value of the number of nickels you need in the answer. The "slacker" Java statement would be:

    6.    displayResult("You need " + numberOfNickels + " nickel(s).");
      but you have decided to impress your boss (me), by writing code which would print:
         you do not need any nickels.
         you need 1 nickel.
      or
         you need n nickels.

      (where "n" is the String equivalent of any number equal to 2 or more), under the respective conditions that (numberOfNickels is zero), (numberOfNickels is one), or (numberOfNickels is bigger than or equal to two). Assuming that all values of numberOfNickels from zero to 10 are equally likely, what is the code you would use to replace the one "slacker line of code"? Note: The last statement clearly indicates that the most common case is when numberOfNickels is larger than 1. Exceptional CS students will take advantage of this fact.

      if (numberOfNickels >= 2)
          displayResult("you need " + numberOfNickels + " nickels.");
      else if (numberOfNickels == 1)
          displayResult("you need 1 nickel");
      else
          displayResult("you do not need any nickels.");
       

  3. (code interpretation-25 points) The following code is neither intuitive nor well designed, but contains many of the constructs we've studied. The ability to "read code" is normally a skill which is highly related to the ability to "write code", so, to the best of your ability, trace the flow of the following code. That is, after compiling the code, you enter the command "java TraceMe", walk through the commands which Java executes, in the order that Java executes them. Hint: create a table showing the value of each data field as you go through the program.

  4.    class TraceMe {
         public static int methodA(int x) {
            if (x > 5)
               return (x-4);
            else
               return (x+2);
         } // end methodA

         public static void main(String [] args) {
             int n = 4;
             int x = 6;
             do {
                 switch (x) {
                     case 1:  n *= 3;
                              break;
                     case 3:  n -= 6;
                              break;
                     default: n++;
                              break;
                 }
                 x = methodA(n);
                 System.out.println("x= " + x + " and n = " + n);
             } while (n > 0);
          } // end main

   } // end TraceMe
 
All Java programs begin by executing the main method, which begins by setting n = 4 and x = 6. Since x = 6, the default case of the switch block is executed, so n is incremented to 5 and we break from the switch block. The value of x is set to methodA(5) = 7, since the if test is false (5 is NOT less than 5). We hit the print line, which yields x = 7 and n = 5. Since 5 > 0, we repeat the loop body. With less detail we proceed:
 
Event
x
n
start of second loop:
7
5
switch(7)
7
6
x = methodA(6) = 2, then print these values and repeat
2
6
switch(2)
2
7
x = methodA(7) = 3, print and repeat
3
7
switch(3)
3
1
x = methodA(1) = 3, print and repeat
3
1
switch(3)
3
-5
x = methodA(-5) = -3, print and stop (n > 0) is false.
-3
-5