Review for Quiz 2

One-page version suitable for printing.

Question 2-1

What is the purpose of a constructor method?

Solution

Question 2-2

The following program uses the Account class we defined in class.

import csbsju.cs160.*;

public class PrintHello {
    public static void main(String[] args) {
        Account a = new Account();
        a.deposit(80.0);
        Account b = a;
        b.withdraw(20.0);
        b = new Account();
        b.deposit(40.0);
        IO.println(a.getBalance());
    }
}
What does this program print?

Solution

Question 2-3

Write a program that reads a name from the user and displays the number of lower-case r's occurring in the name.

Name? Carl Bryan Burch
You have 3 r's.
You'll want to use the instance methods length() and charAt() defined in the String class. Your program's interface should be identical to the above transcript.
import csbsju.cs160.*;

public class PrintHello {
    public static void main(String[] args) {


    }
}

Solution

Question 2-4

Write a method that, given an Account, generates and returns a duplicate account holding the same amount of money. Use the Account object interface described as follow.

Constructors
Account() Creates a new account holding no money.
Object methods
double getBalance() Returns the amount of money held in the object account.
void deposit(double amt) Adds amt dollars to the object account's balance.
void withdraw(double amt) Subtracts amt dollars from the object account's balance.
public static Account duplicate(Account acct) {


}

Solution