What is the purpose of a constructor method?
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()); } }
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.
import csbsju.cs160.*; public class PrintHello { public static void main(String[] args) { } }
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.
Account() | Creates a new account holding no money. |
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) { }
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."); } }
public static Account duplicate(Account acct) { Account ret = new Account(); ret.deposit(acct.getBalance()); return ret; }