CPSC 124, Winter 1998

Second Test


This is the second test given in CPSC 124: Introductory Programming, Winter 1998. See the information page for that course for more information.

The answers given here are sample answers that would receive full credit. However, they are not necessarily the only correct answers. In some cases, I give more detailed answers here than would be necessary to get full credit.


Question 1: Define the term constructor, and give a specific example of the type of task that might be performed by a constructor.

Answer: A constructor is a special kind of subroutine in a class that is called when an object of that class is created. (A constructor can be recognized because it has the same name as the name of the class, and it has no return type, not even void.) Although a constructor can do anything that a programmer wants to put in it, its usual task is to initialize an object that has just been created. For example, the constructor for the BouncingBall class that we used in lab sets the starting position, velocity, color, and size of a new BouncingBall object.


Question 2: Assume that the rectangle on the right [not shown in this answer sheet] is 100 pixels tall and 200 pixels wide. Draw the picture that would be produced by the following paint() method, being careful to show all the figures in their correct sizes and positions.

            public void paint(Graphics g) {
               g.drawOval(10,10,80,80);
               g.drawOval(110,10,80,80);
               g.fillRect(20,40,60,20);
               g.fillRect(120,40,60,20);
               g.fillRect(40,20,20,60);
            }

Answer: The figure shows two circles and three filled-in rectangles. The rectangles are arranged to show a "plus sign" inside one circle and a "minus sign" inside the other circle. The picture is shown below. (In this picture, the large rectangle is the original 100-by-200 rectangle provided in the question. It is not drawn by the commands in the above method.)

Solution to Question 2


Question 3: Write a complete class named VoteCounter that can be used to keep track of the votes on a yes/no question. The class should contain two instance variables to count the number of yes votes and the number of no votes. It should have a method voteYes() that is called to cast a "yes" vote, and a method voteNo() that is called to cast a "no" vote. Finally, it should have a method, getWinner(), to report whether ``yes'' or "no" got the most votes. This method should return 1 if "yes" has more votes, 2 if "no" has more votes, or 0 if both have the same number of votes.

Answer: The class is very simple, containing just the two variables and the three methods described. (Note that the class is not a complete program. It just represents a vote-counting mechanism that could be used by programs that need to count yes/no votes.)

           public class VoteCounter {
           
              private int yesCount = 0;   // The number of "yes" votes 
                                          //        that have been counted.
              private int noCount  = 0;   // The number of "no" votes 
                                          //        that have been counted.
              
              public void voteYes() {  // Register a "yes" vote.
                 yesCount++;
              }
              
              public void voteNo() {   // Register a "no vote.
                 noCount++;
              }
              
              public int getWinner() {   // Check which got the most votes.
                 if (yesCount > noCount)
                    return 1;
                 else if (yesCount < noCount)
                    return 2;
                 else
                    return 0;
              }
              
           } // end class VoteCounter
 

Question 4: State what this applet does and briefly explain why.

        class TestApplet extends Applet
                           implements MouseMotionListener {
            int A = 0, B = 0;
            public void init() {
               addMouseMotionListener(this);
            }
            public void paint(Graphics g) {
               g.setColor(Color.red);
               g.fillRect(A,B,20,20);
            }
            public void mouseDragged(MouseEvent evt) {
               A = evt.getX();
               B = evt.getY();
               repaint();
            }
            public void mouseMoved(MouseEvent evt) {
            }
         }    // end class TestApplet
         

Answer: This applet lets the user drag a red square around the applet. Whenever the user moves the mouse, while holding down the mouse button, the square moves so that its upper left corner is at the position of the mouse. This happens because the applet listens for mouseDragged events, which occur when the user holds down the mouse button and moves the mouse. When this happens, the mouseDragged() method sets the variables A and B, which specify the location of the square, to the x- and y-coordinates of the mouse. It also calls repaint() so that the square will reappear in its new location.


Question 5: Suppose that you are given a class, FileReader, that includes the following subroutines:

Write a complete program that gets the first ten lines from a file and prints them out on the screen. However, if the file contains fewer than ten lines, you should only print out as many lines as it contains. Ask the user for the name of the file. Use an object of type FileReader to read the lines from the file.

Answer:

           public class TenLines {
           
              public static void main(String[] args) {
              
                 FileReader file;   // Object to use for accessing the file.
                 String fileName;   // Name of file, to be entered by the user.
                 String line;       // One line from the file.
                 String lineCount;  // Number of lines that have been read from the file.
                 
                 TextIO.put("Enter name of file: ");
                 fileName = TextIO.getln();
                 
                 file = new FileReader(fileName);
                 
                 lineCount = 0;
                 while (lineCount < 10) {
                    if (file.atEndOfFile())  // If no more lines to read...
                       break;                //     exit the while loop prematurely.
                    line = file.getNextLine();
                    lineCount++;
                    TextIO.putln(line);
                 }
                 
              } // end main();
              
           } // end class TenLines
           

Question 6: What does the computer do when it executes the following statement? Try to give as complete an answer as possible.

             Color[]  pallette  =  new  Color[12];

Answer: This is a declaration statement, that declares and initializes a variable named pallette of type Color[]. The initial value of this variable is a newly created array that has space for 12 items. To be specific about what the computer does: It creates a new 12-element array object on the heap, and it fills each space in that array with null. It allocates a memory space for the variable, pallette. And it stores a pointer to the new array object in that memory space.


Question 7: Write a complete subroutine that finds the largest value in an array of ints. The subroutine should have one parameter, which is an array of type int[]. The largest number in the array should be returned as the value of the subroutine.

Answer:

          public static int getMax(int[] list) {
          
                // Find and return the largest item in the array, list.
             
             int max = list[0];  // This is the largest item seen so far.
             
             for (int i = 1; i < list.length; i++) {
                   // Look at each item in the array.  If the item is
                   // bigger than max, then set max equal to the item.
                 if (list[i] > max)
                    max = list[i];
             }
             
             // At this point, max is the largest item in the whole array.
             
             return max;
             
          } // end subroutine getMax


Question 8: Suppose that the following class is being used to store data about some lakes:

          class LakeData {
             String name;    // The name of the lake.
             double volume;  // Cubic miles of water in the lake.
             int depth;      // Maximum depth, in feet.
          }

Suppose that data about 50 lakes has already been stored in the array

             LakeData[] lakes = new LakeData[50];

(a) Write a code segment that will print the name of every lake in the array that has a depth of 100 feet or greater.

(b) Write a code segment that will compute and print the total volume of the water in all 50 lakes.

Answer:

   (a)       System.out.println("Lakes with depth of 100 feet or more are:");
             for (int i = 0; i < 50; i++) {
                if (lakes[i].depth >= 100)
                   System.out.println(lakes[i].name);
             }
             
             
   (b)       double total;  // Amount of water in lakes.
             for (int i = 0; i < 50; i++)
                total += lakes[i].volume;
             System.out.println("The total volume is " + total);
            

Question 9: One of the examples in Section 4.2 in the text discusses the possibility of a Shape class in which one of the existing Shape objects can be selected at any give time. The text says, "Suppose that shapes can be 'selected,' and you want to keep track of which shape is currently selected. A static variable, selectedShape, could be added to the class to keep track of which shape is currently selected. (Make sure you understand why it is static!)" Why must selectedShape be static?

Answer: There is only one selected shape, so we only want one selectedShape variable. If a variable is static, there is only one variable, which belongs to the class. If it is non-static, then each object has its own version of the variable.


Question 10: Explain how events are used in Java programming. What, specifically, must a programmer include in a program in order to deal with events?

Answer: Events, such as mouse-clicks and button-presses, occur asynchronously, outside the control of the program. A program includes event-handling methods that are called when an event occurs. These methods react to events in a way that depends on the state of the program. To handle events in a Java program, a programmer must write a class that implements the appropriate event-listener interface, such as MouseListener or ActionListener. The interface lists one or more event-handling methods that must be defined in the class. An object belonging to that class is then capable of listening for events. Before it actually hears any events, the object must be also registered as a listener with a method such as addMouseListener().


Question 11: Object-oriented programming is supposed to make it easier to design a program to perform a given task. Explain what is meant by object-oriented programming, and discuss what it offers to help a programmer who is confronted with a complex programming task.

Answer: In object-oriented programming, objects are used to represent things and concepts in the real world. This can help make programs easier to write, since the programmer can analyze a problem to determine what objects need to be represented and what those objects have to be able to do. Furthermore, the objects will be modules that can be worked on independently from one another, to some extent. This helps to divide a complex problem into manageable parts. Inheritance also helps to simplify complex programming tasks. Inheritance makes it possible to reuse old work by creating a subclass and making just the necessary additions and modifications to adapt it to a new problem. In addition, when the programmer needs several classes that share some similarities, the shared part can be coded once in an abstract class, and all the other classes can be written as subclasses of that class.


David Eck, 6 November 1998