CPSC 124, Spring 2017: Sample Answers to Quiz #7

These are sample answers only. Often, answers that are less
detailed than the ones given here can still receive full credit.

Question 1. In Java GUI programming, what is meant by a layout manager, and what does a BorderLayout, in particular, do?

Answer. A layout manager is an object that is responsible for setting the sizes and locations of the components that are contained in a JPanel (or other container). A layout manager implements some policy for laying out the components. For example, a BorderLayout can place one large component in the center, with up to four other components arranged along the four sides of the panel.

Question 2. GUI programming is "event-driven." What are events, and how, briefly, are they handled in Java?

Answer. Events are generated by user actions such as pressing a key on the keyboard or dragging the mouse (or by other things outside the program such as a timer or a network connection). To handle events in Java, a programmer writes event-handling methods that will be called by the system when events occur. For example, a MouseListener is an object containing methods to be called in response to events generated by the mouse. In order to respond to events, the event handler must be set to "listen" for the events, using a method such as panel.addMouseListener(listener).

Question 1. Suppose that the arrays students and grades are defined as shown below, and they have already been filled with data about students in some course, so that students[s] is the name of student number s, and grades[s][q] is the grade for student number s on quiz number q.

Write a code segment that will print out the name of every student whose average grade on the five quizzes is 90 or higher.

          String[] students = new String[50];
          double[][] grades = new double[50][5];

Answer.

System.out.println("The following students have an A on quizzes:");
for (int s = 0; s < 50; s++) {
    double total = 0;
    for (int q = 0; q < 5; q++) {
        total = total + grades[s][q];
    }
    double average = total / 5;
    if (average >= 90) {
        System.out.println( students[s] );
    }
}

Since there are only 5 columns in the array, it's also easy to solve this problem without using the inner for loop:

System.out.println("The following students have an A on quizzes:");
for (int s = 0; s < 50; s++) {
    double total = ( grades[s][0] +  grades[s][1] +  grades[s][2] + 
                            grades[s][3] +  grades[s][4] );
    double average = total / 5;
    if (average >= 90) {
        System.out.println( students[s] );
    }
}