Docsity

Public Quantity - Data Structures - Solved Exams, Exams of Data Structures and Algorithms

Toggle sidebar
bg1
CS 61B: Data Structures (Autumn 2006)
Midterm I
Solutions
Problem 1. (6 points) Java bugs.
public class Quantity {
public String thing; // The thing being measured.
public double amount; // Its numerical quantity.
// Constructor.
public Quantity(String thingString, double amount) {
thing = thingString;
this.amount = amount;
}
// Constructor for thing with quantity 100. Calls the other
constructor.
public Quantity(String thingString) {
this(thingString, 100.0);
}
public static void main(String[] args) {
Quantity q = new Quantity("I love Java this much: ");
System.out.println(q.thing + q.amount);
}
}
Problem 2. (7 points) Inheritance.
a. Meow
b.
What up fool?
Meeeeow!
c. Compile-time error. (Tomcat t = c; needs a cast.)
d. Meeeeow!
e. Compile-time error. (The Cat class does not have a method with the signature
greet(Cat).)
f. Run-time error. (Attempt to cast a Siamese object to a Tomcat.)
g. Compile-time error. (Cannot create an instance of the abstract class Cat.)
pf3

Partial preview of the text

Download Public Quantity - Data Structures - Solved Exams and more Exams Data Structures and Algorithms in PDF only on Docsity!

CS 61B: Data Structures (Autumn 2006)

Midterm I

Solutions

Problem 1. (6 points) Java bugs.

public class Quantity { public String thing; // The thing being measured. public double amount; // Its numerical quantity. // Constructor. public Quantity(String thingString, double amount) { thing = thingString; this. amount = amount; } // Constructor for thing with quantity 100. Calls the other constructor. public Quantity(String thingString) { this (thingString, 100.0); } public static void main(String[] args) { Quantity q = new Quantity("I love Java this much: "); System.out.println( q .thing + q .amount); } }

Problem 2. (7 points) Inheritance.

a. Meow

b.

What up fool? Meeeeow!

c. Compile-time error. (Tomcat t = c; needs a cast.)

d. Meeeeow!

e. Compile-time error. (The Cat class does not have a method with the signature

greet(Cat).)

f. Run-time error. (Attempt to cast a Siamese object to a Tomcat.)

g. Compile-time error. (Cannot create an instance of the abstract class Cat.)

Problem 3. (7 points) The heap and the stack.

Problem 4. (5 points) Creating a Doubly-Linked List.

This sample solution builds the list backward, from tail to head. That way, no special

cases are needed to handle a zero-length array or an array whose ints are all zero.

public static DListNode makeList(int[] counts) {