COSC 135B Exam 2 Practice Problems answers
Tom Linton, Fall 2000, Central College
  1. Write four different Java statements that each add 1 to integer variable x.

  2. x = x+1;
    x++;
    ++x;
    x += 1;
  3. Write Java statements to accomplish each of the following:
    1. Assign the sum of x and y to z and increment the value of x by 1 after the calculation. Use only one statement.

    2. z = x++ + y;
    3. Test if the value of the variable count is greater than 10. If it is, print "Count is greater than 10".

    4. if (count > 10)
         messageBox("Count is greater than 10");
    5. Decrement the variable x by 1, then subtract it from the variable total. Use only one statement.

    6. total -= --x; or total = total - --x;
    7. Calculate the remainder after q is divided by divisor and assign the result to q. Write this statement two different ways.

    8. q = q % divisor; or q %= divisor;
  4. Determine the values of each variable after the calculation is performed. Assume that when each statement begins executing, all variables are integers, product = 5, x = 3, and quotient = 100.
    1. product *= x++;

    2. after execution, product = 15, x = 4 and quotient = 100.
    3. quotient /= ++x;

    4. after execution, quotient = 25, x = 4 and product = 5.
  5. What does the following code fragment print in the TextArea named output?

  6.      int y, x = 1, total = 0;
         while ( x <= 4 ) {
            y = x * x;
            output.append( " " + y-- );
            total += y;
            x++;
         }
         output.append( "\nTotal is " + total );
     1 4 9 16
    Total is 26
  7. Write a for loop that prints the following table of values (including the header rows) in the TextArea named output:
N N^2 N^3
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
output.setText("");
String header = " N " + "N^2" + "N^3";
output.append(header + "\n\n");
for ( int N = 1; N <= 5; N++){
   output.append(" " + N + " " + Format.justify('c',N*N,3) +
       Format.justify('c', N*N*N, 3);
}
  1. Note that if the variable someString is a String, the Java statement someString += "more stuff"; is equivalent to the Java statement someString = someString + "more stuff";  Use this fact to complete the for loop below, which is suppose to print all of the integers from 1 to 100 that are multiples of 2 or multiples of 5.
    1. String answer = "2";
      for ( int k = 3; k <= 100; k++) {
          if ( (k%2 == 0) || (k%5 == 0))
              answer += ", " + k;
      }
      System.out.println(answer);
  2. Assume that output is a TextArea. What is displayed by the following code fragment?
    1. int row = 4, column;
      output.setText("");//erase any text
      while ( row >= 1 ) {
         column = 1;
         for (column = 1; column <= 5; column++ ) {
            if ( row % 2 == 1 )
               output.append( "<" );
            else
               output.append( ">" );
         }
         row--;
         output.append("\n");
      }
      The output displayed is:
      >>>>>
      <<<<<
      >>>>>
      <<<<<
  3. Determine the output for each of the following when x is 9 and y is 11 and again 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. I 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 )

    2.    if ( y > 10 )
            System.out.println( "*****" );
         else
            System.out.println( "#####" );
      System.out.println( "$$$$$" );
      when x=9 and y=11, the output is:
      *****
      $$$$$
      when x = 11 and y = 9, the output is:
      $$$$$
    3. if ( x < 10 ) {

    4.    if ( y > 10 )
         System.out.println( "*****" );
      }
      else {
         System.out.println( "#####" );
         System.out.println( "$$$$$" );
      }
      when x=9 and y=11, the output is:
      ****
      when x = 11 and y = 9, the output is:
      #####
      $$$$$
  4. Modify the following code to produce the output shown. Use proper indentation techniques. You may not make any changes other than inserting braces ( "{" and "}" ) and changing the indentation of the code. The compiler ignores indentation in a Java program. I have eliminated the indentation from the following code to make the problem more challenging. Note: It is possible that no modification is necessary.
    1. if ( y == 8 )
      if ( x == 5 )
      System.out.println( "@@@@@" );
      else
      System.out.println( "#####" );
      System.out.println( "$$$$$" );
      System.out.println( "&&&&&" );
    2. Assuming x = 5 and y = 8, the following output is produced:

    3.  
      @@@@@
      $$$$$
      &&&&&
      Only indentation conventions need to be applied.
      The code produces this output as it is given. Here is
      properly indented code:
      if ( y == 8 )
         if ( x == 5 )
            System.out.println( "@@@@@" );
         else
            System.out.println( "#####" );
      System.out.println( "$$$$$" );
      System.out.println( "&&&&&" );

       
    4. Assuming x = 5 and y = 8, the following output is produced:

    5.  
      @@@@@ Here, we can just group a large
      collection of code in the else clause:
      if ( y == 8 )
         if ( x == 5 )
            System.out.println( "@@@@@" );
         else {
            System.out.println( "#####" );
            System.out.println( "$$$$$" );
            System.out.println( "&&&&&" );
         }

       
    6. Assuming x = 5 and y = 8, the following output is produced:

    7.  
      @@@@@
      &&&&&
      Here, we can just group a medium
      collection of code in the else clause:
      if ( y == 8 )
         if ( x == 5 )
            System.out.println( "@@@@@" );
         else {
            System.out.println( "#####" );
            System.out.println( "$$$$$" );
         }
      System.out.println( "&&&&&" );

       
    8. 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.

    9.  
      #####
      $$$$$
      &&&&&
      We want the else to match the first if, so use braces to make this so:
      if ( y == 8 ){
         if ( x == 5 )
            System.out.println( "@@@@@" );
      }
      else {
         System.out.println( "#####" );
         System.out.println( "$$$$$" );
         System.out.println( "&&&&&" );
      }
  5. Consider the problem of writing a Java program to draw the figure below. Note: Each row of this figure is 5 characters wide, and contains 1, 3 or 5 asterisks in the center. There are 9 rows in the figure.
*
***
*****
*
*
*
*
*
*
    1. Define a method named makeStars( ), which has as input a single integer, say numStars, and returns a String that is 5 characters wide and contains numStars many asterisks in its center. For example, makeStars(3) should return the String " *** ". If you use Format.justify in your method, you will avoid some subtle problems, such as whether makeStars(4) should be " ****" or "**** ". If the input is larger than 5, or less than zero, your method should return the String "error".

    2. public String makeStars(int k) {
         if (k>5 || k<0)
            return "error";
         String answer="";
         for (int numstars=1; numstars <= k; numstars++)
            answer = answer + "*";
         return Format.justify('c',answer,5);
      }
    3. Assuming that your makeStars method is defined and that output is a TextArea, complete the following code fragment so that it draws the arrow above. Each (non-empty) case in your switch block MUST have the form:
      1. output.append( makeStars(x) + "\n" );
        break;
      for some value of x (an integer). Here is the start of your arrow drawing code fragment:
       
        output.setText("");//erase the old text
        for (int row = 1; row <= 9; row++ ) {
           switch(row) {
              case 1: case 4: case 5: case 6: case 7: case 8: case 9:
                 output.append( makeStars(1) + "\n");
                 break;
              case 2:
                 output.append( makeStars(3) + "\n");
                 break;
              case 3:
                 output.append( makeStars(5) + "\n");
                 break;
           }// end switch
        }// end for loop
  1. 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 method, named encrypt, that will encrypt (encode) a single four-digit integer so that it may be transmitted more securely. Your method should have one (four-digit or less) integer input and return the encrypted integer, which is defined as follows:
  2. Write a separate method named decrypt. that inputs an encrypted four-digit integer and returns the decrypted version (i.e. the input is a coded number and the output is the original number). For both methods, you should check to insure that the inputs are not more than 4 digits long (think about integer division by 1000 or 10000 to complete this test). If they are, return the value -1 (a common programming technique is to return -1, when outputs should be positive, to indicate an error).
      public int encrypt( int regularNumber) {
         //test the input for four digits
         if (regularNumber / 10000 > 0)
            return -1;
         //extract the digits
         int digit1,digit2,digit3,digit4;
         digit1 = regularNumber % 10;
         regularNumber /= 10;
         digit2 = regularNumber % 10;
         regularNumber /= 10;
         digit3 = regularNumber % 10;
         digit4 = regularNumber / 10;
         //add the 7 to each digit
         digit1 = (digit1 + 7) % 10;
         digit2 = (digit2 + 7) % 10;
         digit3 = (digit3 + 7) % 10;
         digit4 = (digit4 + 7) % 10;
         //rebuild the coded number, incorporating the swapped digits
         return (digit2*1000 + digit1*100 + digit4*10 + digit3);
      }

      For the decrypt method, we reverse the steps:

      public int decrypt( int codedNumber) {
         //test the input for four digits
         if (codedNumber / 10000 > 0)
            return -1;
         //extract the digits and unswap them
         int digit1,digit2,digit3,digit4;
         digit3 = codedNumber % 10;
         codedNumber /= 10;
         digit4 = codedNumber % 10;
         codedNumber /= 10;
         digit1 = codedNumber % 10;
         digit2 = codedNumber / 10;
         //subtract the 7 from each digit, but make sure the result is positive
         digit1 = (digit1 - 7 + 10) % 10;
         digit2 = (digit2 - 7 + 10) % 10;
         digit3 = (digit3 - 7 + 10) % 10;
         digit4 = (digit4 - 7 + 10) % 10;
         //rebuild the regular number.
         return (digit4*1000 + digit3*100 + digit2*10 + digit1);
      }

  3. What is returned by (double) (3 / 4);        how about (double) 3 / 4; explain.

  4. The first gives 0.0, since 3 / 4 = 0. The second gives 0.75, since it is equivalent to ( (double) 3 ) / 4, which is the same as 3.0 / 4, which is double division.
  5. In Java, how do you say "if N is negative or N is even, add 5 to N, otherwise decrease N by 1"?

  6. if ( (N < 0) || ( N % 2 == 0) )
       N += 5;
    else
       N--;
  7. The following code is neither intuitive nor well designed, but contains many of the constructs we've studied. To the best of your ability, trace the flow of the following code. That is, walk through the commands which Java executes, in the order that Java executes them, keeping track of the values of the variables. Hint: create a table showing the value of each data field or variable as you go through the program. Assume that the GUI is defined, that results is a TextArea, and trace what happens as the user clicks the button.
    1.  
      public class TraceMe extends GBFrame {
      public static int methodA(int x) {
            if (x > 5)
               return (x-4);
            else
               return (x+2);
         } // end methodA

         public static void buttonClicked(Button myButton) {
            int n = 4;
            int x = 6;
            while (n > 0) {
                switch (x) {
                   case 1:
                      n *= 3;
                      break;
                   case 3:
                      n -= 6;
                      break;
                   default:
                      n++;
                      break;
                }//end switch
                x = methodA(n);
                results.append("x= " + x + " and n = " + n);
            }// end while
          } // end buttonClicked

       } // end TraceMe
    Originally, n = 4 and x = 6, when we enter the while loop. Since n = 4 > 0, we do the body of the while loop. A switch on 6, causes the default case to execute, so n is incremented to 5 and we break from the switch statement. Next, x = methodA(5) = 7 (since the if test is false, we return 5 + 2). We'll print "x = 7 and n = 5" in the TextArea and go back to the while loop test. Since n = 5 > 0, we switch on x = 7, which sets n = 6 by the default case. Then x = methodA(6) = 2, and we append "x = 2 and n = 6" to the TextArea. Back to the while test, which is true, so we do the while loop body and switch on 2, yielding the default case again, so n = 7, and x = methodA(7) = 3, so "x = 3 and n = 7" is appended. A switch on 3, causes case 3 to execute, so n becomes 1. Then, x = methodA(1) = 3, so "x = 3 and n = 1" is appended. Since 1 > 0, we switch on 3 and set n = n - 6 = -5. Now, x = methodA(-5) = -3, and "x = -3 and n = -5" is appended to the TextArea. Finally, the while test fails, and the buttonClicked method is over.

  8. Write a method named isLessThan that takes two double inputs, x and y, and returns true when x < y, and false when x >= y.
    1. public boolean isLessThan(double x, double y) {
         return (x < y)
      }
  9. Assuming the following definition of the method scramble:
    1. public int scramble(int egg)
         egg = (egg * 35) % 4;
         return egg;
      }


    what are the final values of the variables liquid and yolk, after the following lines of code are executed?

       int liquid, yolk = 5;
       liquid = scramble(yolk);

    yolk is still equal to 5 (the copy passed to the method scramble has no effect on the variable, only the value of the variable) and liquid = (5*35) % 4 = 3.