York University Winter 2003 / Midterm
Faculty of Pure and Applied Science
Department of Computer Science COSC1030.03
February 23, 2003
This is a closed book, 2-hour test. Fill in your personal data below and wait.
You may use pen or pencil.
No questions are allowed during the test. Do your best.
Once the test starts, verify that you have 15 pages.
Some test papers will be selected randomly and copied before being returned to students.
NAME (Family, First) / M MWF 10:30TurpinNTR 14:30Toptsis
PW 19 Hofbauer
PRISM LOGIN
/ csSTUDENT NUMBER
CIRCLE REGISTERED SECTION
/M N P
A subset of String Methods is given in this table. You may need some of them.(Each is invoked on a string s.) / char charAt(int p)
Returns the character at position p in s.
boolean equals(String t)
Returns true if s and t have equal contents. / int compareTo(String t)
Returns a negative number if s<t, zero if s=t, and a positive number if s>t .
int indexOf(String t)
Looks for the string t within s (as above), starting at the beginning of s. Returns index where found or –1 if not found. / String trim()
Returns s with any leading & trailing white-space removed.
String substring(int start,int pastEnd)
Returns a string extracted from s starting from the character at start up to and excluding character at pastEnd. / String replace(char x,char y)
Returns a copy of s with all occurrences of character x in it replaced by character y.
String substring(int start)
Returns a substring of s that begins at start and extends to the end of s. / String toUpper/LowerCase()
Returns a copy of s with all characters converted to upper / lower case.
Group A/8 / Group B/8 / Group C/14 / Total/30
GROUP - A 8 points
A-1 2 points> Assume the following is a method of String class (therefore it would be invoked
on a string s). Explain in one clear English statement what this method does.
public boolean mystery(String aString)
{
boolean returnValue = false;
int start = 0;
int length1 = this.length();
int length2 = aString.length();
while (((start + length2) <= length1) & !returnValue)
{ if (aString.equals(this.substring(start, start + length2)))
returnValue = true;
else
start++;
}
return returnValue;
}
Your Answer:
Answer: mystery is like indexOf except that it returns a Boolean indicating whether the substring aString was found, instead of an int indicating where it was found.
2 parts to answer (1 point each) :
- like indexOf
- return type differs from indexOf
A-23 points Based only on the partial class definitions given below, draw a diagram
showing inheritance (is-a), association (has-a), and realization relationships among the
mentioned classes or interfaces (and java.lang.Object). Just connect the classes/interfaces
with the 3 appropriate lines/arrow types. No credit is given to arbitrary lines that do not
convey the type of the relationship. Similarly no credit is given if you identify wrong
relationships. Show only the relationships that you can deduce from the code below. Do
not invent more relationships.
public class Person
{ … }
public class Student extends Person
{ …
}
public class Professor extends Person
{ … }
public class University
{ …
private BankAccount mainAccount;
}
public Interface Financial
{ …}
public BankAccount implements Financial
{ … }
public SavingsAccount extends BankAccount implements Financial
{ … }
Answer:
Inheritance or is-a relationships:
Person is-a Object
University is-a Object
BankAccount is-a Object
Student is-a Person
Professor is-a Person
SavingsAccount is-a BankAccount
Associations or has-a relationships:
University has-a BankAccount
Realization relationships:
BankAccount realizes Financial
SavingsAccount realizes Financial
A diagram is ok as long as either links and arrows are according to UML or are correctly labeled. Drawing just lines with arbitrary arrows has no points.
A-33 points Study the following classes stored in the same directory:
import type.lang.*;
public class Father
{
public Father()
{
IO.println("Father’s constructor");
}
}
import type.lang.*;
public class Child extends Father
{
public Child()
{
IO.println("Child’s constructor");
}
}
import type.lang.*;
public class GrandChild extends Child
{
public GrandChild()
{
IO.println("GrandChild’s constructor");
}
}
Now consider the following application stored in the same directory as the above classes.
import type.lang.*;
public class App1
{
public static void main (String[] args)
{
Father myFather = new GrandChild();
}
}
What is the output after we run App1?
Your Answer: Answer Father’s constructor
Child’s constructor
GrandChild’s constructor
GROUP - B < 8 points
B-12 points> Study the following classes stored in the same directory.
import type.lang.*;
public interface Greetings
{
public void sendMyRegards();
}
import type.lang.*;
public class Johnson implements Greetings
{
public void sendMyRegards()
{
IO.println("Greetings from the Johnson Family");
}
}
import type.lang.*;
public class Smith implements Greetings
{
public void sendMyRegards()
{
IO.println("Greetings from the Smith Family");
}
}
Now consider the following application stored in the same directory as the above classes.
import type.lang.*;
public class App2
{
public static void main ( String[] args )
{
Greetings g1 = new Johnson();
Greetings g2 = new Smith();
g1.sendMyRegards();
g2.sendMyRegards();
}
}
What is the output after we run App2?
Your Answer: Answer:
Greetings from the Johnson Family
Greetings from the Smith Family
B-2 < 6 points > Study the following classes stored in the same directory.
public class Person
{
public Person(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public String describeSelf()
{
return "I am a person.";
}
public String getGreeting()
{
return "Hello!";
}
private String name;
}
public class Student extends Person
{
public Student(String name, String studentNumber)
{
super(name);
this.studentNumber = studentNumber;
}
public String getStudentNumber()
{
return studentNumber;
}
public String describeSelf()
{
return "I am a student.";
}
public String getGreeting(String additionalGreeting)
{
return super.getGreeting() + " " + additionalGreeting;
}
private String studentNumber;
}
Now consider the following class stored in the same directory as the above classes.
import type.lang.*;
public class App3
{
public static void main (String[] args)
{
// BODY OF THIS METHOD IS GIVEN IN EACH PART BELOW
}
}
For each of parts (a) - (f) below, give the output or express the kind of errors that we may encounter
if we run the App3 program with the implementation as given in each case. Treat each of (a) - (f)
separately and independently: the code in one part has nothing to do with the code in another part.
If you think that there would be an error during compiling, write COMPILETIME ERROR. If you think
the program would compile, but there would be an error while it is running, write RUNTIME ERROR
as your answer. Do not add comments or explanations. An answer that is only partially correct will
not receive partial credit.
Marking Scheme: 1 point if completely correct, otherwise 0 (for each part).
(a) BODY OF METHOD main:
Person p1 = new Person("Peter");
Person p2;
Student s1 = new Student("Susan", "99988877");
Student s2;
p1 = s1;
IO.println(p1.getName());
Answer: Susan
(b) BODY OF METHOD main:
Person p1 = new Person("Peter");
Person p2;
Student s1 = new Student("Susan", "99988877");
Student s2;
p2 = s1;
IO.println(p2.getGreeting());
Your Answer:
Answer: Hello!
(c) BODY OF METHOD main:
Person p1 = new Person("Peter");
Person p2;
Student s1 = new Student("Susan", "99988877");
Student s2;
p2 = s1;
IO.println(p2.getGreeting("How are you?"));
Your Answer:
Answer: COMPILETIME ERROR
(d) BODY OF METHOD main:
Person p1 = new Person("Peter");
Person p2;
Student s1 = new Student("Susan", "99988877");
Student s2;
p2 = s1;
IO.println(p2.describeSelf());
Your Answer:
Answer: I am a student.
(e) BODY OF METHOD main:
Person p1 = new Person("Peter");
Person p2;
Student s1 = new Student("Susan", "99988877");
Student s2;
p2 = s1;
IO.println(p2.getStudentNumber());
Your Answer:
Answer: COMPILETIME ERROR
(f) BODY OF METHOD main:
Person p1 = new Person("Peter");
Person p2;
Student s1 = new Student("Susan", "99988877");
Student s2;
p2 = s1;
s2 = (Student)p2;
IO.println(s2.describeSelf());
Your Answer:
Answer: I am a student.
GROUP - C 14 points
C-17 points > Recall the Queue class that you saw in the case study. It had 4 methods:
public boolean empty();
public void insert(Object newItem);
public Object remove();
public Object peek();
Recall the BankAccount class and its methods from the textbook. It had two constructors and three
methods:
Public BankAccount();
public BankAccount(double initialBalance);
public void deposit(double amount);
public void withdraw(double amount);
public double getBalance();
In this question you will write some methods for a Bank class which uses the Queue and
BankAccount classes. The Bank class just has a list of accounts which it manipulates. Only a
few of its methods are shown here.
import java.util.*;
public class Bank
{
private ArrayList accounts; // Holds all the accounts in the bank.
/**
Constructs a bank having all the accounts in the passed queue.
@param accountQueue queue holding all accounts for the new bank object.
*/
public Bank(Queue accountQueue)
{ // You will write this
}
/**
Removes and returns the BankAccounts with the smallest and largest
balances (these may be the same account). In the case of multiple
BankAccounts having the same smallest (and/or largest) balance, return
the first such occurrence. This method is called only when the list of
accounts is not empty. However, you do not have to check for this
condition.
@return an array of bank accounts containing the accounts with smallest and
largest balances. (Hint: The size of the returned array is always 2.)
*/
public BankAccount[] removeSmallestLargest()
{ // You will write this method
}
}
(a) Implement the constructor for the Bank class.
public Bank(Queue accountQueue)
{ // Hint: just empty the queue into the ArrayList called accounts.
accounts = new ArrayList();
while (!accountQueue.empty())
{
accounts.add(accountQueue.remove());
}
}
(b) Implement the removeSmallestLargest() method
public BankAccount[] removeSmallestLargest()
{
public BankAccount[] removeSmallestLargest()
{
BankAccount smallest = (BankAccount)accounts.get(0);
BankAccount largest = smallest;
int smallestIndex = 0;
int largestIndex = 0;
for (int i = 1; i < accounts.size(); i++)
{
BankAccount temp = (BankAccount)accounts.get(i);
if (temp.getBalance() < smallest.getBalance())
{
smallest = temp;
smallestIndex = i;
}
if (temp.getBalance() > largest.getBalance())
{
largest = temp;
largestIndex = i;
}
}
BankAccount smallestLargest[] = new BankAccount[2];
smallestLargest[0] = smallest;
smallestLargest[1] = largest;
/**
Remove the one that is at a higher index first
so that it does not change the index for the other one
*/
int first = Math.min(smallestIndex, largestIndex);
int second = Math.max(smallestIndex, largestIndex);
accounts.remove(second);
if (first != second)
accounts.remove(first);
return smallestLargest;
}
}
C-27 points > Recall Assignment 1 where you implemented the game of Red Dog. The game of Red
Dog is a card game played on blackjack-sized tables with a shoe generally holding six decks of cards.
Suit values are represented with values 0 to 3; card values are represented with values 2 to 14; a deck
of cards has 52 cards. The instance variables of a shoe object are its decks of cards, next card to be dealt,
and a random generator used to shuffle the cards in the shoe. Implement the requested components of
classShoe. Method toString is not shown below.
import type.lang.*;
/**
The Shoe class encapsulates a shoe, which in gambling lingo
is a plastic or wooden box containing several decks of playing cards.
The implementation of method shuffle is not shown here.
*/
import java.util.Random;
public class Shoe
{
private int numDecks;
private Card[] deck;
private int nextCardToDeal;
private Random generator;
private static final int MAX_SUIT_VALUE = 3;
private static final int MAX_CARD_VALUE = 14;
private static final int MIN_CARD_VALUE = 2;
private static final int NUM_CARDS_IN_A_DECK = 52;
/**
Construct a shoe with the cards from a single deck.
*/
public Shoe ()
{ // Your will write this part
}
/**
Construct a shoe with the cards from n decks.
@param n is the number of card decks.
(Precondition: n must be > 0)
*/
public Shoe (int n) throws IllegalArgumentException
{ // Your will write this part
}
/**
Deal a card from the shoe. If the shoe is empty, return null.
@return the next card in the shoe
*/
public Card dealCard ()
{
// Your code to be written in part c.
}
public void shuffle ()
{ …
}
}
As a memory aid, here is the signature of the constructor from the Card class:
public Card (int suit, int value) throws IllegalArgumentException
(a) Write the implementation of method dealCard below.
public Card dealCard()
{
if (nextCardToDeal >= NUM_CARDS_IN_A_DECK * numDecks)
return null;
return deck[nextCardToDeal++];
}
(b) Write the implementation of the default constructor below.
Method 1:
public Shoe()
{
this(1);
}
Method 2: like the non-default constructor (see ©)
// fill shoe with cards
numDecks = 1;
deck = new Card[NUM_CARDS_IN_A_DECK];
// initialize shoe full of cards
int m = 0;
for (int suit = 0; suit <= MAX_SUIT_VALUE; suit++)
for (int value = MIN_CARD_VALUE; value <= MAX_CARD_VALUE; value++)
deck[m++] = new Card(suit,value);
(c) Write the implementation of the non-default constructor below.
public Shoe(int n) throws IllegalArgumentException
{
if (n < 1 )
throw new IllegalArgumentException
("Number of decks must be > 0.”);
// fill shoe with cards
numDecks = n;
generator = new Random();
nextCardToDeal = 0;
deck = new Card[NUM_CARDS_IN_A_DECK*numDecks];
// initialize shoe full of cards
int m = 0;
for (int deckNumber = 0; deckNumber < numDecks; deckNumber++)
for (int suit = 0; suit <= MAX_SUIT_VALUE; suit++)
for (int value = MIN_CARD_VALUE; value <= MAX_CARD_VALUE; value++)
deck[m++] = new Card(suit,value);
}
- 1 -