Docsity

Final Exam with Answer Key - Problem Solving - Fall 2005 | CS 18000, Exams of Computer Science

Toggle sidebar
bg1
CS 180 Fall 2005 Final Exam
There are 40 multiple choice questions. Each one is worth 2 points. There are 6
programming questions. Each one is worth 20 points.
Answer the multiple choice questions on the bubble sheet given and the programming questions on the
exam booklet.
Fill in the Instructor, Course, Signature, Test, and Date blanks. For "Instructor" put your Recitation
Instructor's last name. For "Course" put CS 180. For "Test" put Final.
08:30 recitation in REC 122: Matt Carlson
08:30 recitation in BRNG B254: Andy Scharlott
09:30 recitation in BRNG B268: Nick Sumner
11:30 recitation in REC 308: Rimma Nehme
01:30 recitation in UNIV 103: Alvin Law
Fill in the bubbles that correspond to your name, section and student ID in the bubble sheet. For your
section number, use 0830, 0930,1130, or 0130 -- based on the start time of your Friday recitation.
For your student ID, use the 10 digit ID number on your student ID card. DO NOT USE YOUR SOCIAL
SECURITY NUMBER!
Exams without names will be graded as zero. Only the answers on the bubble sheet will be counted.
The questions will be discarded.
For the programming questions create a Java class that would compile without error.
Comments are nice, but are not required.
Recitation Start Time: _________________________________
Student Last Name: __________________________________
Student First Name: __________________________________
1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18

Partial preview of the text

Download Final Exam with Answer Key - Problem Solving - Fall 2005 | CS 18000 and more Exams Computer Science in PDF only on Docsity!

CS 180 Fall 2005 Final Exam

There are 40 multiple choice questions. Each one is worth 2 points. There are 6

programming questions. Each one is worth 20 points.

Answer the multiple choice questions on the bubble sheet given and the programming questions on the

exam booklet.

Fill in the Instructor, Course, Signature, Test, and Date blanks. For "Instructor" put your Recitation

Instructor's last name. For "Course" put CS 180. For "Test" put Final.

08:30 recitation in REC 122: Matt Carlson

08:30 recitation in BRNG B254: Andy Scharlott

09:30 recitation in BRNG B268: Nick Sumner

11:30 recitation in REC 308: Rimma Nehme

01:30 recitation in UNIV 103: Alvin Law

Fill in the bubbles that correspond to your name, section and student ID in the bubble sheet. For your

section number, use 0830, 0930,1130, or 0130 -- based on the start time of your Friday recitation.

For your student ID, use the 10 digit ID number on your student ID card. DO NOT USE YOUR SOCIAL

SECURITY NUMBER!

Exams without names will be graded as zero. Only the answers on the bubble sheet will be counted.

The questions will be discarded.

For the programming questions create a Java class that would compile without error.

Comments are nice, but are not required.

Recitation Start Time: _________________________________

Student Last Name: __________________________________

Student First Name: __________________________________

Multiple Choice Questions (2 points each):

  1. Which of the following statements regarding Java is false? a. Java uses a compiler b. A Java program compiles into machine language c. Java uses an interpreter d. Java is a programming language
  2. Which of the following is a legal variable name in Java? a. 1stInput b. long c. NumberOfPlayers d. player.
  3. What is the output produced by the following code? int n = 2; System.out.print((++n) + " " + (n++) + "\n"); System.out.println(n); a. 2 3 4 b. 3 3 4 c. 3 3 4 d. 2 3 4
  4. What is the output produced by the following code? String temp = "Hello CS180 Class"; System.out.print(temp.substring(8).trim()); a. 180Class b. 180 Class c. Hello CS d. Nothing - this causes a compiler error
  5. In a Java program, you read the following statement that compiles and executes. Cookie cookie = new Cookie("chocolate chips"); What can you conclude? a. Cookie is the name of a class. b. cookie is a primitive type variable. c. The Cookie class must have a constructor that has one formal parameter of type String. d. a and c
  1. A constructor ... a. must have the same name as the class it is declared within. b. is used to create objects. c. may be declared private d. All of the above
  2. Which of the following is a valid constructor header for a HousePet class: a. public HousePet HousePet() b. public void HousePet() c. public HousePet() d. public void HousePet( int numLegs )
  3. Suppose you have a class with a method, public int average( int first, int second ) Which of the following methods cannot be added to the class? a. public double average( int first, int second, int third ) b. public double average( int first, int second ) c. public double average( double first, double second ) d. public double average( int[] numbers )
  4. What is the type of an array initialized with the following value? { { {59.385}, {49.6} }, { {986.35}, {583.64}, {12.85} } } a. double [][][] b. double [][] c. double [[]] d. int[][]
  5. What is the result of the following method? public static void printStrings() { Integer[] num = new Integer[5]; Integer sum = 0; for ( int index = 0; index < num.length; ++index ) sum += num[index]; System.out.println( sum ); } a. "null" is printed b. "0" is printed c. A java.lang.ArrayIndexOutOfBoundsException is thrown d. A java.lang.NullPointerException is thrown
  1. Which of the following is added by the Java compiler as the first statement in class B's constructor? public class B extends A { private int num; public B() { num = 0; } ... } a. super() b. A() c. this() d. nothing is added automatically
  2. Which best describes overloading and overriding? a. In overloading, methods must have the same signature. In overriding, methods must have different signatures. b. In overloading, methods must have different signatures. In overriding, methods must have the same signature. c. In overloading and overriding, methods must have different signatures. d. In overloading and overriding, methods must have the same signature.
  3. Given ... public void methodA() throws Exception1, Exception2, Exception Which of the following can override methodA() in a derived class? a. public void methodA() throws Exception b. public void methodA() throws Exception c. public void methodA() throws Exception1, Exception2, Exception3, Exception d. public void methodA() throws Exception1, Exception
  4. When defining a method you must include a ___________ to declare any exception that might be thrown but is not caught in the method. a. try block b. finally block c. catch block d. throws-clause
  1. Which of the following statements is true regarding Vectors with no specified base type? a. A base type is needed because Java needs to know how to allocate memory b. No base type is needed because Java will use the Object class as a base type c. If a base type is not specified the code will not compile d. No base type is needed because Vectors default to storing String objects
  2. Given a singly-linked list that contains Strings (as defined in the book and class), what will the following code segment do? Note: head points to the head of the list and the list contains at least 2 nodes. ListNode curNode = head; do { System.out.println(curNode.data); curNode = curNode.next; } while(curNode != null); a. Print out the data of each item on the list b. Print out the data of the head node only c. Nothing - this will cause a compile error d. Nothing - this will cause an ArrayIndexOutOfBounds exception.
  3. Given the following generic class, which of the statements will compile? public class Sample { private T data; public void setData(T new) { data = new; } public T getData() { return data; } } a. Sample a = new Sample(); b. Sample b = new Sample(); c. Sample c = new Sample; d. Sample d = new Sample;
  4. Which of the following is false regarding recursion and iteration? a. Any recursive method can be rewritten in an iterative form (with a loop) b. Recursive calls take time and consume additional memory c. In general, recursive algorithms lead to better performance than iterative algorithms d. A recursive method is a method that calls itself
  1. What is the value of doSomething(2,3) given the following code fragment? public int doSomething(int a, int b) { if (b==1) return a; else return a + doSomething(a,b-1); } a. 2 b. 4 c. 6 d. the program generates a run time error (infinite recursion)
  2. Select the recursive function which defines the sequence 5, 8, 11, 14, 17, 20 .. a. public int s(int n) { if (n == 0) return 5; else return (s(n) + 3); } b. public int s(int n) { if (n == 0) return 5; else return (3n + 5); } c. public int s(int n) { if (n == 0) return 5; else return s(3n + 5); } d. public int s(int n) { if (n == 0) return 5; else return 3 + s(n-1); }
  3. Which method call will display a JFrame object named myFrame on the screen? a. myFrame.showToScreen() b. myFrame.display() c. myFrame.setEnabled( true ) d. myFrame.setVisible( true )
  1. How might you extract a number from a JTextField object named text? a. int n = text.getValue() b. int n = text.getInt() c. int n = text.parseInt() d. int n = Integer.parseInt( text.getText() )
  2. What does the trim() method do? a. returns a string with all blanks removed b. returns a string with leading blanks removed c. returns a string with leading and trailing blanks removed d. shrinks the capacity of the vector down to the current size of the vector
  3. Given the following class, public class Demo extends JFrame implements ActionListener { ... Container contentPane = getContentPane(); JButton button = new JButton("button"); ... } Which of the following correctly adds the button to the frame? a. contentPane.add(button); b. add(button); c. Demo.add(button); d. add(button, BorderLayout.NORTH);
  4. In an applet-class definition, the ________ method takes the place of the constructor. a. paint() b. init() c. main() d. run()
  5. What method must appear in Demo given the following declaration? public class Demo extends JFrame implements ActionListener a. windowClosed() b. actionPerformed() c. getActionCommand() d. addActionListener()
  6. In a Java GUI, the purpose of classes which implement the ActionListener interface is to: a. describe the graphical display of GUI items such as JButtons b. control the organization of items displayed in the GUI c. respond to the events caused by GUI items such as JButtons d. none of the above
  1. Which of the following statements is true when comparing the pros and cons of using an array versus using a java Vector? I. An array is fixed in length when declared whereas a Vector is dynamic in size and can be resized. II. An array’s values can be indexed easily with the [] brackets. There exists no such equivalent for a Vector. III. A Vector can store objects of any type where as an array can only store primitive types. a. I only b. II only c. II and III only d. I and II only
  2. Given the method definition below, what is the result of calling f(3, 5)? public int f(int x, int y) { if (x < 0 || y > 10) return x + y; else return f(x-1, y+1); } a. 2 b. 8 c. 10 d. the method call f(3,5) will not terminate
  3. Which of the following is true about the use and purpose of the Iterator interface? I. An iterator allows a programmer to efficiently search for an element in a java Vector. II. An iterator allows a programmer to perform a set operation on each element of a data structure such as a java Vector or a linked list. III. An iterator provides an easy way to sort the elements of a Vector or linked list. a. I only b. II only c. III only d. II and III only

import java.util.*;

public class RatioCalculator {

public RatioCalculator() {

try {

int widgets, defective;

double ratio;

System.out.println( "Enter number of widgets produced:" );

Scanner keyboard = new Scanner( System.in );

widgets = keyboard.nextInt();

if( widgets<0 ) {

throw new NegativeNumberException( "widgets" );

System.out.println( "How many were defective?" );

defective = keyboard.nextInt();

if( defective<0 ) {

throw new NegativeNumberException( "defective" );

ratio = divide( widgets, defective );

System.out.println( "One in every " + ratio +

" widgets is defective" );

catch( DivideByZeroException e ) {

System.out.println( "Congratulations! A perfect record!" );

catch( NegativeNumberException e ) {

System.out.println( "Cannot have a negative number of " +

e.getMessage() );

System.out.println( "End of program" );

public double divide( double num, double den ) throws

DivideByZeroException

if( den == 0 ) throw new DivideByZeroException();

return ( num/den );

public static void main( String[] args ) {

new RatioCalculator();

class NegativeNumberException extends Exception {

public NegativeNumberException( ) { super(); }

public NegativeNumberException( String msg ) { super(msg); }

class DivideByZeroException extends Exception {

public DivideByZeroException( ) { super(); }

public DivideByZeroException( String msg ) { super(msg); }

import java.util.*;

public class Test

public static void main(String[] args)

Scanner keyboard = new Scanner(System.in);

Vector budgets = new Vector();

String input;

int thisBudget, highBudget, lowBudget, totalBudget;

// read all input

do {

System.out.print("Enter budget (-1 to finish): ");

input = keyboard.nextLine();

thisBudget = Integer.parseInt(input);

if (thisBudget!=-1)

budgets.addElement(thisBudget);

} while (thisBudget != -1);

// calculate totalbudgets, low and high

highBudget = -1;

lowBudget = 101;

totalBudget = 0;

for(int i=0; i<budgets.size(); i++)

totalBudget+=budgets.elementAt(i);

if (budgets.elementAt(i) < lowBudget)

lowBudget = budgets.elementAt(i);

if (budgets.elementAt(i) > highBudget)

highBudget = budgets.elementAt(i);

// display result

System.out.println("\nAverage Budget: " +

totalBudget/budgets.size());

System.out.println("High Budget: " + highBudget);

System.out.println("Low Budget: " + lowBudget);

} // end main

} // end class

3. Assume we have a class called Node which can be used to build a linked list. Each Node contains an array of

integer scores that are within a certain range. For example you may use the 1st^ Node to store all the scores in the F

range, the 2nd^ Node to store all the scores in the D range, the 3rd^ Node to store all the scores in the C range, etc. A

Node contains the following variables and methods:

class Node { private int[] values; // these values are sorted in ascending order private Node next; public Node(int[] values, Node next) public int[] getValues() public void setValues(int[] values) public Node getNext() public void setNext(Node next) }

Now, complete the class Gradebook below. Gradebook contains a linked list of the above Node class. Each

node represents a non-overlapping group of grade values and each successive Node contains a range of group

values greater than the previous Node. For this problem, you will not be responsible for constructing the

Gradebook itself; you may assume the Gradebook is properly constructed for you already. You only need to

complete the method gradeExists(int), which returns true if the grade exists within the Gradebook, and false

otherwise. Since the values array is sorted, you should take advantage of this and perform a binary search for

the specified value. Points will be deducted for inefficient algorithm. You may assume the Gradebook

contains at least one grade value in one Node (that is, the variable gradebook is never null). You may write

helper methods as needed.

class Gradebook

Node gradebook;

* You don’t need to bother with constructors and other methods

* TODO: complete the method gradeExists

* use binary search to look for grade in the linked list

* return true if grade is found, false otherwise

4. Write a RECURSIVE method to determine whether a given string is a palindrome or not. A string is a

palindrome if it reads the same forward and backward. You can assume the given string will contain only

alphabetical characters. Ignore the case of the letters and skip over blanks when you make the comparison. For

example:

The word “cow” is not a palindrome.

The phrase “A man A plan A canal Panama” is a palindrome.

public class Palindrome

public Palindrome()

//constructor stuff goes here

public boolean isPalindrome(String s)

if (s.length() <= 1)

return true; // base case

else

if (s.toLowerCase().charAt(0) ==

s.toLowerCase().charAt(s.length() - 1))

return isPalindrome(s.substring(1, s.length() - 1));

else

return false;

} // end isPalindrome()

public static void main(String[] args)

Palindrome p = new Palindrome();

String s = "a man a plan a canal panama";

String target = s.replace(" ", "");

if (p.isPalindrome(s))

System.out.print("string '" + s +"' is a polyndrome");

else

System.out.print("string '" + s +"' is NOT a polyndrome");

} // end Palindrome

5. Given that JLabels have some interesting features, it would be nice to be able to try out various possible

JLabels without making a new program each time. Thus, you are to create a complete Java GUI program that

allows the user to enter the text of JLabels, possibly with multiple lines, and then preview them. You should

use the following design:

The user can enter text in the text area. Then, when the button is pushed, this text is displayed as a label in the

label preview. Note that there is a title label at the top, as well as a label for both the text entry and label

preview regions. Also, the text entry and preview regions are the same size. In addition, the button is centered

and does not take up more space than its text needs.

The text area should wrap words around lines, but does not need to consider scrolling.

Title

Button

Text Area Label Preview

Enter Text: Label Preview: