Review for Quiz 2

Question 2-1

What is the purpose of a constructor method?

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?

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) {


    }
}

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) {


}

Solutions

Solution 2-1

Its purpose is to initialize the instance variables of a newly allocated object.

Solution 2-2

60.0

Solution 2-3

public class PrintHello {
    public static void main(String[] args) {
        IO.print("Name? ");
        String name = IO.readLine();
        int count = 0;
        for(int i = 0; i < name.length(); i++) {
            if(name.charAt(i) == 'r') ++count;
        }
        IO.println("You have " + count + " r's.");
    }
}

Solution 2-4

public static Account duplicate(Account acct) {
    Account ret = new Account();
    ret.deposit(acct.getBalance());
    return ret;
}