CS 177 Spring 2005 Exam Ics180/Spring2007Web/sampl…  · Web view2007. 4. 24. · The word...

33
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. 1

Transcript of CS 177 Spring 2005 Exam Ics180/Spring2007Web/sampl…  · Web view2007. 4. 24. · The word...

CS 177 Spring 2005 Exam I

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

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

6. Which of the following while loops is equivalent to the do-while loop? Hint: you may want to draw a flow chart to figure out the answer.

do

{

y = x + 7;

x++;

} while (x < 9);

a.y = x + 7;

x++;

while (x < 9)

{

y = x + 7;

x++;

}

b. while (x < 9)

{

y = x + 7;

x++;

}

y = x + 7;

x++;

c. while (x <= 9)

{

y = x + 7;

x++;

}

d. Both a and b

7. How many times is the phrase "Happy New Year" printed by the following code?

int a = 6;

int b = 12;

while (a < b)

{

System.out.println("Happy New Year");

a += 2;

b -= 2;

}

a. 1

b. 2

c. 3

d. 4

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

9. 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 )

10. 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 )

11. 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[][]

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

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

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

15. Given ...

public void methodA() throws Exception1, Exception2, Exception3

Which of the following can override methodA() in a derived class?

a. public void methodA() throws Exception4

b. public void methodA() throws Exception3

c. public void methodA() throws Exception1, Exception2, Exception3, Exception4

d. public void methodA() throws Exception1, Exception4

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

17. Aside from the Scanner class, which of the following classes can be used for text-file file input?

a. BufferedReader

b. ObjectInputStream

c. StringTokenizer

d. none of the above

18. With a BufferedReader, which of the following is true when the readLine() method is called when the end of the file is reached?

a. the String returned is null

b. the String returned is the empty string, ""

c. the String returned is "EOF"

d. an IOException is thrown

19. Which of the following are reasons to close a file as soon as possible after its use?

I. Closing a file prevents the file from accidentally being corrupted.

II. Closing a file which a program has written to will allow a BufferedReader to open the file at a later time and read the written information.

III. Closing a file will prevent the file from accidentally being deleted by the operating system.

a. I only

b. II only

c. I and II only

d. I and III only

20. Using the read() method in class BufferedReader returns an int. Which of the following is true about the int returned?

I. The int represents the actual integer in the file being read.

II. The int represents the ASCII value of the character in the file being read.

III. The int represents the end of file marker if the int returned is -1.

a. I only

b. II only

c. III only

d. II and III only

21. Which of the following is the correct way to create a vector to hold Strings

with an initial capacity of 10 items?

a. Vector v = new Vector<10>;

b. Vector v = new Vector[10];

c. Vector v = new Vector(10);

d. Vector v = new Vector(10);

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

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

24. 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;

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

26. 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)

27. 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 (3*n + 5);

}

c. public int s(int n)

{

if (n == 0)

return 5;

else

return s(3*n + 5);

}

d. public int s(int n)

{

if (n == 0)

return 5;

else

return 3 + s(n-1);

}

28. 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 )

29. Consider the following function

void RecEm(int i)

{

if ( i < 8 )

{

RecEm(i);

}

}

How many times is RecEm invoked by the function call RecEm(3) ?

a. 2

b. 5

c. 7

d. This is an example of infinite recursion.

30. What method is used to respond to such things as button clicks?

a. public void actionHeard( ActionEvent a )

b. public void actionPerformed( ActionEvent a )

c. public void actionListener( Action a )

d. public void actionHeard( ActionListener a )

31. Suppose you need to create a GUI with the following design:

A stretches horizontally and has a fixed height.

B stretches vertically and has a fixed Width.

C takes up as much space as possible in all directions.

What is the best single Layout to use?

a. BorderLayout

b. GridLayout

c. FlowLayout

d. CardLayout

32. 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() )

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

34. 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);

35. In an applet-class definition, the ________ method takes the place of the constructor.

a. paint()

b. init()

c. main()

d. run()

36. 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()

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

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

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

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

Programming Questions (20 points each):

1. You work for a company which produces different types of widgets. Occasionally a widget is produced which is defective. Your boss would like you to write a program, RatioCalculator, which computes the ratio of widgets produced to defective widgets. The input to the program will be from the user, and the program should work as follows:

1. Input the total number of widgets produced.

2. Input the total number of defective widgets produced.

You should implement:

public double divide( int num, int den ) { ... }

to compute the ratio of widgets produced to defective widgets produced.

You should write two Exception classes:

1. DivideByZeroException - thrown if trying to divide by 0

2. NegativeNumberException - thrown if a negative number is given as input

If a ratio can be computed successfully, you should output the ratio as shown in the sample execution.

Be sure to print "End of Program" at the very end of your program.

Three sample runs of the program are given below:

Enter number of widgets produced:

1000

How many were defective?

500

One in every 2.0 widgets is defective.

End of Program

Enter number of widgets produced:

-10

Cannot have a negative number of widgets.

End of Program

Enter number of widgets produced:

1000

How many were defective?

0

Congratulations! A perfect record!

End of Program

2. You are asked to do a survey of the holiday spending for this Christmas. Write a complete Java program that will allow a user to enter a set of budgeted spending and calculate some basic statistics. The integer spending amount will be entered from the keyboard, and you do not know in advance how many entries will be entered. After all budgets have been entered (the user will enter -1 to signal end of input), display the integer mean (average), high budget, and low budget.

Note: You can assume that all input are valid (you do not need to test for non-integers). Only -1 to signal end of input will be out of range. You can also assume that at least one number will be entered.

You must use the Vector class to store the set of numbers so that you can expand your program later to include other statistics.

Sample execution:

Enter budget (-1 to finish): 100

Enter budget (-1 to finish): 75

Enter budget (-1 to finish): 37

Enter budget (-1 to finish): 82

Enter budget (-1 to finish): -1

Average Budget: 73

High Budget: 100

Low Budget: 37

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

*/

public boolean gradeExists(int grade)

{

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.

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.

6. New York Times keeps two sorted lists for the most popular fiction books and non fiction books based on the number of copies sold. These are stored in two text files TopFictionBooks.txt and TopNonFictionBooks.txt. Each file contains a list where each line follows the format of:

Title, Author, copies sold

Title contains multiple words separated by blanks and no punctuations. Author contains first name followed by last name. It may also contain initials. Copies sold is an integer. The three fields are separated by commas.

Write a MergeList class that will open both files and print to the screen the merged result of the two lists showing the title, the author, and the number of copies sold from the most popular to the least popular. You should handle common file errors such as FileNotFound or IOException by printing a message and exiting. You can assume the lists are not empty and the entries are properly formatted.

Sample data for TopFictionBooks.txt:

Mary Mary, James Patterson, 34567

At First Sight, Nicholas Sparks, 32400

Light from Heaven, Jan Karon, 30123

Predator, Patricia Cornwell, 28100

The Lighthouse, P. D. James, 28049

C

B

A

Title

Button

Text Area

Label Preview

Enter Text:

Label Preview:

PAGE

21