Category Archives: Java

Gridworld Bug Subclasses

 SlowBug class

A SlowBug is a Bug that poops Rocks instead of Flowers when it moves. However, since Rocks take a little bit longer to get out than Flowers do, a SlowBug takes THREE timesteps (three calls to act) before it is able to move like a normal bug .

A SlowBug is a Bug has the following behaviors and attributes:

  • a SlowBug has an instance variable called counter that is increased each time it acts
  • the default constructor for this class will set the bug’s color to green.
  • It also has a constructor that takes a color parameter :

    public SlowBug(java.awt.Color col)

  • After a SlowBug has waited two turns without doing anything, it acts exactly like a normal bug..
    At the end of each act, whether or not the bug has done anything, it increments counter variable.
  • the move method works the exact same as a regular Bug’s move, except instead of pooping a Flower in the space it leaves, it poops a Rock the same color as itself.

If you want, you can download SlowBug.gif and drag it into Eclipse or Bluej to use that image instead of the default Bug image.
The final result of running SlowBug would be something like the picture below.

 

FastBug

    FastBug is exactly like a normal bug, except it acts twice each “timestep” instead of just once. For example, in one timestep it will:

  • check if it can move, and if it can, it will move. If it can’t it will turn.
  • After it moves or turns, it will check if it can move again, and if it can, it will move. If it can’t, it will turn.

A FastBug is a Bug and should contain the following behaviors:

  • the default constructor for this class will set the bug’s color to red. It should also make it start out in a random direction (not always facing North like a normal bug does).
  • the act method should behave as described above
  • a FastBug is so fast, the flowers it leaves behind are already almost wilted when they come out. To do this, you will need to modify the move method so that the Flower it generates is not the same color as the FastBug, but five “shades” darker. To increase the darkness, use the Color class’s non-static darker()method five successive times on your color before passing it in to the Flower constructor.

If you want, you can download FastBug.gif and drag it into Eclipse to use that image instead of the default Bug image.

 

If you want an A, you must do FIsh:

Fish

Last year’s Marine Biology Case Study was similar to GridWorld, but it worked with Fish objects that have a 1/7 chance of breeding (or, more accurately, spontaneously generating children) each timestep and a 1/5 chance of dying each timestep. A Fish cannot move backwards, and our Fish will not turn, move, or generate children diagonally; it will only use the 4 cardinal directions North, South, East, and West. For this part of the lab, we are going to create a similar Fish in GridWorld.

A Fish is an Actor and should contain the following behaviors and attributes:

  • a shared, static instance variable: private static int nextAvailableID = 1; 
    A static variable is one that ALL instances of the class share. So the first fish that is made will initialize the static variable to 1; the others will keep using it.
  • a private int instance variable: private int myID;
  • a private static double instance variable for probabilityOfBreeding that is initialized to 1.0/7.0 and a private double instance variable for probabilityOfDying that is initialized to 1.0/5.0
  • Also, your fish should not die during the first 5 steps of the program.
  • the default constructor for this class should
    • set the Fish’s color to a random color. Use (Math.random()*256)typecast as an int to get random numbers between 0 and 255 for the Color constructor.
      • import java.awt.* to be able to initialize a new Color(double r, double g, double b);where r,g,b are each ints between 0 and 255 inclusive and represent the red, green and blue values of the color
    • The constructor should also make the Fish start out in a random direction (from North, South, East, or West…no other directions are allowed for a Fish). In the constructor, set      myID=nextAvailableID++;
      This means the first fish will get the ID 1, the next will get 2, the next will get 3, etc. Since nextAvailableID is static, it is shared amongst all fish.
  • override the public String toString() method as follows:
    public String toString()
    {
        return myID + " facing " + getDirection();
    }
  • protected boolean breed() method should be written that:
    • First calls Math.random() and checks to see if the number is the random number generated is >= probabilityOfBreeding. If it is, return false (your Fish did not breed this time).
    • Otherwise, if the random number was < probabilityOfBreeding, that means we will try to breed in all the empty locations in front, behind, to the left, and to the right of us.
      To do this, first find out how many empty locations you have above you, to your right, to your left, and below you.

      • If you have zero empty spaces above you, to your right, to your left, and below you, return false (you didn’t have an open space to generate children to so you couldn’t breed).
      • If you have one to four empty spaces, you will need create new Fish objects, then have them place themselves in the empty locations. When you are finished generating all the children you can, return true (you successfully bred).
  • protected void move() method should be written that:
    • checks for all valid, empty spaces above you, to your right, and to your left (Fish don’t move backwards, so we don’t check below you), then picks one of those to move to and goes there, changing directions to face the spot you are moving to (for instance, if you are going to an empty spot to your left, you turn left after you go there). If there are no empty locations you can go to, just stay still.
      Note: If you look through the GridWorld API in the Location class and Grid interface, you will find some methods very helpful in writing this method.
  • the act method should be overridden with the following code:
    public void act()
    {
    // Try to breed.
    if ( ! breed() )
    move(); 
    // Did not breed, so try to move.// Determine whether this fish will die in this timestep.
    if ( Math.random() < probabilityOfDying )
    removeSelfFromGrid();
    }

If you want, you can download Fish.gif and drag it into Eclipse to use that image instead of the default Actor image.
It can be kind of hard to tell what is happening, but if you move your mouse over a Fish in the grid you can see the toString() printed out, which will tell you which unique fish id you are looking at. Since breeding, dying, and moving are random, there is no set way to guarantee what your grid will look like, but here is how mine looked after it ran a few times

 

Java String Assignments -intro-1

Java String Assignments

These exercises are introductory methods that require use of basic String methods including

  • substring()
  • length()
    • “abc”.length() – >3
  • concatenation

 

public boolean sameStrings(String string1 ,String string2)

Description: This method returns true if string1 and string2 are the same. Use the ‘.equals()’ method.

Method Call return value/output
sameStrings(“foo”,”f”) false
sameStrings(“foo”,”foo”) true
sameStrings(“abc”, “cba”) false

public boolean any2Same(String a,String b, String c)

Description: This method returns true if any 2 of the strings are the same. Remember: Use the ‘.equals()’ method.

Method Call return value/output
any2Same(“xz”,”f”, “xz”) true
any2Same(“xz”,”f”, “xt”) false
any2Same(“xz”,”xz”, “fff”) true
any2Same(“xtz”,”abc”, “abc”) true
any2Same(“xtz”,”a^c”, “a!c”) false

public String firstThirdLettters(String str)

Description: This method returns the first and third letters of str concatenated together.

Method Call return value/output
firstThirdLettters(“foo“) “fo”
firstThirdLettters(“abcdefg”) “ac”
firstThirdLettters(“ad!kjkj”) “a!”

public boolean sameFirst2Letters(String a, String b)

Description: This method returns the first 2 letters of a and of b are the same .

Method Call return value/output
sameFirst2Letters(“axt”, “axjjj”) true
sameFirst2Letters(“1%3″ , “3$1″) false
sameFirst2Letters(“a~dd” ,”~adt” ) false

public String concatTwice(String str)

Description: This method returns str concatenated with itself .

Method Call return value/output
concatTwice(“foo”) “foofoo”
concatTwice(“a”) “aa”
concatTwice(“abcdd”) “abcddabcdd”

public String concatWithComma(String str)

Description: This method returns str concatenated with itself and with a comma in between

Method Call return value/output
concatWithComma(“foo”) “foo,foo”
concatWithComma(“a”) “a,a”
concatWithComma(“abcdd”) “abcdd,abcdd”

public String sandwich(String bread, String meat)

Description: This method is easiest to understand by looking at the sample calls below

Method Call return value/output
sandwich(“a“,”b“) aba
sandwich(“xy“,”ab“) xyabxy
sandwich(“hi“,”bye“) hibyehi

public int lengthTimesTwo(String str)

Description: This method returns the length of str times 2.

Method Call return value/output
lengthTimesTwo(“foo”) 6
lengthTimesTwo(“a”) 2
lengthTimesTwo(“abcdd”) 10

 String prePendFoo(String str)

Description: prepend “foo ” to the input and return the concatenation.

Method Call return value/output
prePendFoo(“abc”) “foo abc”
prePendFoo(“x”) “foo x”
prePendFoo(“abcdd”) foo abcdd”

public int sumOfLengths(String a, String a)

Description: This method returns the sum of the lengths of String a and String b .

Method Call return value/output
sumOfLengths(“ab”, “jk1”) 5  ie ( 2 +3)
sumOfLengths(“jj”, “”) 2 (ie 2 + 0)
sumOfLengths(“a~dd” ,”6″ ) 5  ie ( 4  + 1)


**public String concat5Times(String str)

Description: This method returns str concatenated with itself 5 times (Do this with a loop)

Method Call return value/output
concat5Times(“foo”) “foofoofoofoofoo”
concat5Times(“a”) “aaaaa”
concat5Times(“abcdd”) “abcddabcddabcddabcdd”

Pascal’s Triangle Recursion example

Pascal’s Triangle

Pascals Triangle presents a simple formula for expanding binomials. If you think a little bit about how Pascal’s Triangle determines each term, you should see that a recursive method is used!

The animation below demonstrates the recursive nature of Pascal’s Triangle.

Part I

Objective: to employ recursion to be able to print out an entire line of Pascal’s Triangle . Look at the animation, getting a particular term in a line is inherently recursive. This class should throw an ArithmeticException if you attempt to calculate an invalid Term. (quick example of how to throw an Exception)

Hint: You only need to use recusion to get the term of the expansion.

Part II

Now that you can print out an entire line of Pascal’s Triangle. Print out the entire triangle up to some degree ‘n’.

java-recursion-excercises-1

void countDown(int num)

Description: This method prints the numbers from num down to and including on new lines

Method Call output
countDown(5) 5
4
3
2
1
0
countDown(3) 3
2
1
0
void printRev(String s)

Description: This method prints each letter of String s on new lines in reverse order.

Method Call output
printRev(“abcdef”) a
b
c
d
e
f
printRev(“abc”) a
b
c

 

int sumLessthan(int n)

Description: This method returns the sum of all positive integers less than or equal to n

Method Call output
sumLessThan(4)   10 (4+3+2+1)
sumLessThan( 5 )  15 ( 5 + 4 + 3 + 2 + 1)

 

int sumLessthan(int n)

Description: This method returns the sum of all positive integers less than or equal to n

Method Call output
sumLessThan(4)   10 (4+3+2+1)
sumLessThan( 5 )  15 ( 5 + 4 + 3 + 2 + 1)

 

double average( int[] nums, int index)

Description: This method returns the average of all the elements in nums. The parameter ‘idnex’ is used to keep track of how far along you have gone in the array.

Method Call output
average({3,2,1}, 0)   2
average({3,2,2}, 0)    2.333333

Recursion in Java

Recur

bunnyEars2() (try to figure out what goes where the question marks are)

Recursion problems (bunny ears is a good, straight forward one to start with)

 

Sorting Algorithm Assignment

Sorting Algorithm

 

Good Links

 

You will be given a sorting algorithm to research and to present to the class in a powerpoint. Your powerpoint should

  1. in general terms explain how the algo works
  2. show Java code for the algorithm
  3. have an animation demonstrating how the algorithm works (step by step)
  4.  clearly explain how the code (in each line) relates to the code (most important and easy to forget step)
  5. It’s important that you can explain each line of the code
  6. state best,worst, average case for the data and, in particular, state how the original state of data affects run time performance
    1. in order
    2. random
    3. in reverse order

Grading Rubric Algorithm Project


 

 

 

4

3

2

1

  Big Oh

(double weight)

Addresses best/worst/ave cases with clear connection to all aspects of code

 

Addresses best/worst/ave cases  but does not relate to all relevant code Addresses best/worst/ave cases  but does not connect to code/is too general Does not address all 3 cases Big Oh or does not connect to code in meaningful way
 Animation of algorithm(double weight)

 

 

 

Animation is clearly connected to all aspects of code Animation is connected to critical areas of code Animation is not clearly connected to actual code Animation and code are not related to one another
 Overview(double weight)

 

Gives a clear and enlightening overview of how the algo works in general. Overview of algorithm is technically correct and discusses most of the relevant features. Algorithm is vaguely summarized or is not well explicated. Algorithm is not explained in a meaningful way.

 

  

 

 

 

Class Relationships involving interfaces and Abstract Classes

Two Caveats

  1. all instance variables must be explicitly written as “private”
  2. Declare ArrayList’s as type “list”:
    1.  List<Integer> blahBlah = new ArrayList<Integer>()
    2. list-arraylist

 

The classes below represent different ways of representing mathematical  concepts like MathExpressions, Fractions etc. and they all implement the Mathable interface. 

 

graphical_math_object

 

public abstract class GraphicalMathObject

methods

  • public abstract void displayGraphicalRepresentation() ;

public class Fraction extends GraphicalMathObject

This class is used to represent Fractions

Instance Variables

  • private int numerator
  • private int denominator

Constructor : The constructor should initialize both instance variables

  • public Fraction(int num, int denom)

Methods

  • public void displayGraphicalRepresentation() ; (just print out ” I’m a fraction -displayGraphicalRepresentation()”. This is the method that renders a graphical representation of the fraction .
  • fraction-matching
  • private int getGCF() //returns the GCF of numerator and denominator
  • public void simplify()//simplifies the fraction. Note: you must call getGCF()
  • public Fraction clone() //return a clone of the current object (** Extra credit…research this) ( link )
  • plus all of the methods in Mathable (Described at bottom)

public class MathExpression extends GraphicalMathObject

This is a class that is used to represent mathematical expressions like 3x2or 5x2y2 . It contains the methods and variables described below and it must implement Mathable

Instance Variables

  • private int coefficient
  • private List<String> variables
  • private List<Integer> powers

NOTE: you should use the following sytnax

Declare ArrayList’s as type “list”:

  1.  List<Integer> blahBlah = new ArrayList<Integer>()
  2. list-arraylist

Constructor : You can decide how to write the constructor.

  • Just be sure to initialize the instance variables

methods implement all methods of the Mathable Interface in ways that make sense for this class. The idea with Mathable is that you should be able to tell if the objects are either equivalent, exactly the same and that you should be able to return a String representation (data) that uniquely identifies the given mathematical expression.

  • public void addTerm( String term , int power) ) // This is used to represent multiplication, actually and this method adds a term with a power to the object’s list of variables and power to the list of powers. You can not assume that the term does not yet exist in the expression .
    For instance, if the original term were 3x5 and the object called addTerm("y", 6)  the object would then be 3x5y6. Or for another example, if the original term is 2x3z, and  addTerm("z", 5)  the object would be 2x3z11 .
  • public void displayGraphicalRepresentation()  ; (just print out “I”m a MathExpression.: displayGraphicalRepresentation()”). This is the method that draws the MathExpression on the screen like:
  • plus all of the methods in Mathable

Examples

3x2y5

coefficient: 3

variables : [ “x”, “y”]

powers : [ 2, 5]

x1y11

coefficient: 1

variables : [ “x”, “y”]

powers : [ 1, 11]

3y2x5

coefficient: 3

variables : [ “y”, “x”]

powers : [ 5 , 2]

 


Interface : Mathable

  • public String getData( ) ;   represents core mathematical information that defines current object.
  • public boolean exactlyEquals(Mathable other) ;
  • public boolean isEquivalent(Mathable other) ;

Intro To Java Assignments (2013-14)

Arrays II

  • Arrays in Demo
  • Test : June 10th/11th (Arrays and two dimensional arrays)
  • Two Dimensional Arrays
  • The problem with Arrays
  • Array 2 (codingbat)  Do any 18 questions.  You can get extra credit for doing any of the last 4.  EOD Sunday  May 31st
    • All students must do sum67
  • Array Fun 2 (due by EOD Tuesday May 13rd )
  • Array Fun 1 (email to me by EOD Tuesday May 6th)

Arrays

  • short circuiting
  • Array 1 Coding Bat  type questions
  • default values of arrays
  • arrays in memory(value vs reference)
  • swapping values in an array without creating a new array like this coding bat problem–assuming you didn’t make a new array
  • Coding Bat : Array 1 (Thursday April 24th-that’s day of the 2nd class after the April break)
  • Short Circuiting

April 2nd

      • Test (April 2nd/3rd)
      • All coding bat warm up and String 1’s must be completed by then
      • Strings immutable, codingbat.com

 

 

Strings (the basics)

String Cheat Sheet



String str ="ABCDEFG"

String firstLetter = str.substring(0,1)

String firstTwoLetters = str.substring(0,2)

String lastLttr = str.substring(str.length() -1)

String last_2_lttrs = str.substring(str.length() -2 )

String middle_lttr = str.substring(str.length()/2 , str.length()/2 +1)
Unit 2

Extra credit: Looping over Strings

 

Unit I
Deadline the day you return from feb break

coding_bat_matrix


Midterm Quiz

*Wed/Thursday 21st/22nd

      • definitions:
        • pass by value
        • pass by reference
      • C++ memory usage (see last asssessment) . Yes, pretty much same questions with different numbers
      • floating point error
      • understand of whether the following data types are pass by value vs reference in Java
        • int
        • double
        • boolean

 

Account Abstract Class Assignment

This is the first part of a 2 part project.

Person Class

Constructor

  • public Person( String _name , int _age )

instance Variables

  • private String name
  • private int age

 Methods

  • public String  getName()
  • public int compareTo(Person other) { return this.age - other.age; }

account_with_person2_with_arrow

Account – Abstract Super Class

Static Variable(s)

  • private static int nextAccountNum
  • private static int parentCompanyCode = 12810  ;

instance Variables

  • private int  accountNumber// first account number should be 1 
  • protected  double  balance
  • protected  ArrayList<Person> owners

Constructor

  • public Account( double _balance, Person _owner)  // add _owner to ArrayList  owners

Methods

  • public static int getParentCode()
  • public int getAccountNumber()
  • public void deposit(double amount)
  • public double getCurrentBalance()
  • public abstract  boolean withdraw(double amount)
  • public boolean equals(Account other) // are the unique account numbers equals ?
  • public String toString() Output should follow the conventions we have discussed. I will be testing for formatting like this :screenshot.41
  • public int comparesTo(Account other) { return this.accountNumber- other.accountNumber }  (Note that this method has an ‘s‘ )
  • public void addOwner(Person p) //adds P to the ArrayList of owners
  • public ArrayList<Person> getOwners()  //  returns the ArrayList of owners
  • public Person remove( Person p) // this emulates the ArrayList’s remove() method (link) . Remember that that method removes the object and then returns the removed object. In this case, you should remove Person P from the ArrayList of owners

  • CheckingAccount extends Account
  • This class has to do certain things. You can decide the best way to do it. This class should have a way to
    • attempt to withdraw money by writing a check. Every check should have a ‘check number’, which should be an integer. The lowest permissible value for a check number is 100 .  
    • public int writeCheck(double amount) // @ returns the check number of the written check 
    • public boolean cancelCheck(int checkNumber)
      • be able to cancel checks and keep track of the check numbers that have been cancelled
      • when a check is cancelled, the amount associated with that check is added back onto the balance.
      • return true if checkNumber is a valid check number; false otherwise.
  • One solution
    • every time you write a check, you need a new check “#”
    • writeCheck( double amount) - > tries to call this.withdraw(double amount)  . You can then use ArrayLists to store check numbers, associated check amounts , things like that

SavingsAccount extends Account

  • instance variables
    • private double interestRate //  //@ assumes that interest rate is not in decimal format i.e. 1.7 not .017
    • private ArrayList<Double> dailyBalances

    static variables

    • public static final int MINIMUM_BALANCE=100;  // this is the absolute minimum amount of money that must always be in the account
  • methods
      • public boolean withdraw(double amount)  //@override the withdraw() method to ensure that currentBalance  the never gets below MINIMUM_BALANCE
      •   public void updateInterestRate(double newRate) //updates the interestRate
      • public void recordDailyBalance()  // @ record current day’s balance by storing current balance in dailyBalances .
      • public ArrayList<Double> getDailyBalances()  // @ return dailyBalances .
      • public double projectBalance(double timeInYears)  // use the compound interest formula .  Assume that the bank compounds the balance monthly. To learn more about how compound interest really works, click here .
        •   You will need to convert interest rate from something like 1.7%, as an example , to 0.017
      • public  void updateInterestPayment() // @ once a month update account based on average daily balances and interest rate.

    *calculate the average monthly balance
    * multiply balance by the interest rate (remember this must be converted to decimal)
    * add that interest back onto the balance

  • public double getInterestRate() 
  • public String toString() Output should follow the conventions we have discussed. I will be testing for formatting like this : SavingsAccount_toString_v2

CertificateOfDeposit extends SavingsAccount

instance Variables

  • public static final  double EARLY_WITHDRAW_PENALTY= 200 .

 Methods

  • public boolean withdraw(double amount , boolean isEarly )  //@override the withdraw()  and applies penalty to balance

 

Tester file :

import java.util.ArrayList;

public class Tester { 
    boolean verbose = false; //set to true for some expanded occasional error messages


    public Tester() {
        p2("Begin Testing");    
        p2("Version 4");    
        p2("set variable verbose to true if you want some occasional extra tips on errors");    
		p2("********************************************************************") ;
		p2("********************************************************************") ;
        doTest();
    }

    public void doTest(){

        int correct = 0;
        int wrong = 0;
        Person tyler = new Person("tyler", 18);
        Person joe = new Person("joe", 18);
        Person jim = new Person("jim", 17);

        if(tyler.compareTo(joe) == 0)
            correct++;
        else{
            p2("error @person, compareTo()");
            wrong++;
            }
        if(jim.compareTo(joe) == -1)
            correct++;
        else{
            p2("error @person, compareTo()");
            wrong++;
            }
        if(joe.compareTo(jim) == 1)
            correct++;
        else{
            p2("error @person, compareTo()");
            wrong++;
            }
        if( joe.getName().equals("joe"))
            correct++;
        else{
            p2("error @person, getName()");
            wrong++;

            }


        CertificateOfDeposit a = new CertificateOfDeposit(tyler, 120);
        double a_original_bal = a.getCurrentBalance();
        a.addOwner(joe);
        int a_num1 = a.getAccountNumber() ;    
		
		

        if (a_num1 != 1 ){
            wrong++    ;
            p2("First account 's id should be '1' ");
        }
        else 
            correct++;
    

        CertificateOfDeposit a2 = new CertificateOfDeposit(jim, 120);




    if(a2.getAccountNumber() <= a_num1){
            wrong++    ;
            p2("Unique account numbers not working correctly ");
        }
        else 
            correct++;


        if (a.getOwners().size() != 2)
            {
            p2("addOwner() not working ");
            wrong++    ;
            }
        else 
            correct++;

        a.remove(joe);
        if (a.getOwners().size() != 1)
        {
            wrong++ ;    
            p2("error , probably removeOwner() not working ");
        }
        else 
        {
            Person owner = a.getOwners().get(0);
            if(owner.getName().toLowerCase().equals("tyler"))    
                correct++;
            else
                {
                wrong++ ;    
                p2("error , probably removeOwner() not working ");
                }
        }


        if(Math.abs(a_original_bal - 120) > 0.000001)
		{
		p2 ("foo problem with setting  balance");
		wrong++;
		}
        else 
            correct++;


        
        a.deposit(25);
        if(Math.abs(a.getCurrentBalance() - 145) > 0.000001)
        {
            wrong++    ;
            p2("problem with setting  balance");
        }
        else 
            correct++;
        
        
        
        Person rob = new Person("rob", 18);
        CheckingAccount b = new CheckingAccount(rob, 200);
        b.deposit(500);
        b.withdraw(450);
        if( b.equals(a))
        {
        wrong++;    
            p2("Failed equals() test (Many things could cause this)");
        }
        else 
            correct++;

        if( a.equals(a) == false)
        {
        wrong++;    
            p2("Failed equals() test (Many things could cause this)");
        }
        else 
            correct++;


        double balanceNow = b.getCurrentBalance();
        int checkNum = b.writeCheck(4);
        // p2("checkNum : " + checkNum);
           if(checkNum >= 100) 
            correct++;
        else
        {
        wrong++;
        p2("error, Check Numbers cannot be lower than 100") ;
        }
       

        int check2Num = b.writeCheck(4);
        if(check2Num - checkNum == 1)
            correct++;
        else
        {
        wrong++;
        p2("error involving checknumbers. Should increment by 1") ;
        }

        if( balanceNow - b.getCurrentBalance() ==  8)
            correct++;
        else
            {
            wrong++;
            p2("Error involving writing checks and balance...could be various problems");
            if(verbose)
                p2("\t most likely your writeCheck() or withdraw() are the problem");
            }

        balanceNow = b.getCurrentBalance() ;
        int check3Num = b.writeCheck(242.1);

        if(check3Num - checkNum == 2)
            correct++;
        else
        {
        wrong++;
        p2("error involving checknumbers. Should increment by 1,even if the check bounces!") ;
        }

        if(balanceNow  == b.getCurrentBalance())
            correct++;
        else
        {
        wrong++;
        p2("Error involving bounced checks. You cannot withdrawal more than your current balance") ;
        p2("exiting testing program");
        return;
        }


        boolean badChkNum =  b.cancelCheck(50);
        if(badChkNum == false)
            correct++;    
        else
        {
        wrong++;
        p2("Error. cancelCheck on non existent check. Should return false, but didn't") ;
        p2("exiting testing program");
        return;
        }

        int check4Num = b.writeCheck(100);


        b.cancelCheck(check4Num);
        
        double balanceAferCancel = b.getCurrentBalance();
        if( balanceAferCancel == 242)
            correct++;
        else{
            wrong++;
            if(balanceAferCancel == 142)
                p2("cancelCheck() did not update balance. You still have deducted the amount for the check that is now cancelled");
            else
                p2("error , could be various things but most likely relateing to cancelCheck()/deposit()  ");
            }

        

        // if(balanceNow  == b.getCurrentBalance())
        //     correct++;
        // else
        // {
        // wrong++;
        // p2("Error involving bounced checks. You cannot withdrawal more than your current balance") ;
        // }


        Person roochi = new Person("roochi", 12);
        SavingsAccount c = new SavingsAccount(roochi, 110);
        boolean allGood = true;
        if(c.getCurrentBalance()== 110)
            correct++;
        else
        {
            allGood = false;
        wrong++;
        p2("error, could be constructor or getCurrentBalance()") ;

        }
        


        c.withdraw(5);
        if(c.getCurrentBalance()== 105)
            correct++;
        else
        {
            if(allGood )
                p2("error, probably withdraw()");
            else
                p2("error, could be constructor or getCurrentBalance() ") ;
        wrong++;
        }
        
        boolean isNull = false;
        try{
            
            c.addOwner(tyler);
        }
        catch( NullPointerException e){
        isNull = true;    
        
        }
    if(isNull)
        {
        p2("Looks like owners arraylist is null");
        p2("exiting program now, fix nullpointer first");
        wrong++;
        return;
        }
    else
        correct++;


//here 
// public String toString()





        Person james = new Person("Jim Adams II", 12);
        SavingsAccount jamesAcct  = new SavingsAccount(james , 666 );
        jamesAcct.addOwner(new Person("Jane Adams ", 34) );
        jamesAcct.addOwner(new Person("Jim Adams Sr", 35) );
        ArrayList<Person> owners = jamesAcct.getOwners();


        boolean anotherNull = false;
        try{
        jamesAcct.recordDailyBalance();
        }
        catch(NullPointerException e){
        anotherNull = true ;
        wrong++;
        }

    if(anotherNull)
        {
        wrong++;
        p2("NullPointer Exception Error, looks like you never initialized dailyBalances in SavingsAccount");
        p2("Exiting testing program");
        return;
        }
    else
        correct++;


    jamesAcct.updateInterestRate(3.3);

    if(jamesAcct.getInterestRate() == 3.3 )
        correct++;
    else{
        wrong++;
        p2("error, probably re: updateInterestRate()  or possibly getInterestRate()");
        }


    jamesAcct.recordDailyBalance();
    

    jamesAcct.deposit(22);
    jamesAcct.recordDailyBalance();
    jamesAcct.withdraw(100);
    jamesAcct.recordDailyBalance();
    jamesAcct.deposit(330);
    jamesAcct.recordDailyBalance();

     ArrayList<Double>  dailyBalances = jamesAcct.getDailyBalances(); 
    
    if(dailyBalances.get(0)== 666)
        correct++;
    else
        {
        wrong++;
        p2("error @ dailyBalances index 0");
        if(verbose)
            p2("\t\t 1st element of dailyBalances should be 666.00");
        
        p2("exiting testing program, fix daily balances first");
        return;
        }



    if(dailyBalances.get(1)== 666)
        correct++;
    else
        {
        wrong++;
        p2("error @ dailyBalances index 1");
        if(verbose)
            p2("\t\t 2nd element of dailyBalances should be 666.00");
        }
        
    if(dailyBalances.get(2)== 688)
        correct++;
    else
        {
        wrong++;
        p2("error @ dailyBalances index 2");
        if(verbose)
            p2("\t\t 3rd element of dailyBalances should be 666.00") ;
        }

    if(dailyBalances.get(3)== 588)
        correct++;
    else
        {
        wrong++;
        p2("error @ dailyBalances index 3");
        if(verbose)
            p2("\t\t 4th element of dailyBalances should be 588.00") ;
        }


    if(dailyBalances.get(4)== 918)
        correct++;
    else
        {
        wrong++;
        p2("error @ dailyBalances index 4");
        if(verbose)
            p2("\t\t 5th element of dailyBalances should be 918.00") ;
        }




    if( Account.getParentCode()== 12810)
        correct++;
    else{
        wrong++;
        p2("Account.getParentCode() wrong ");
        }

        //toString Tests
        String str = jamesAcct.toString();

    if(str.indexOf("SavingsAccount") == 0 )
        correct++;
    else{
        wrong++;
        p2("toString() should start w/classname. i.e. \"SavingsAccount\" ");
        }
    str = str.toLowerCase();

    if(str.contains("number") )
        correct++;
    else{
        wrong++;
        p2("toString() incorrectly formatted, Account number");
        }

    if(str.contains(jamesAcct.getAccountNumber() +"") )
        correct++;
    else{
        wrong++;
        p2("toString() incorrectly formatted, Account number");
        }

    if(str.contains("balance") )
        correct++;
    else{
        wrong++;
        p2("toString() incorrectly formatted, re: account balance");
        }

    if(str.contains(jamesAcct.getCurrentBalance() +"") )
        correct++;
    else{
        wrong++;
        p2("toString() incorrectly formatted, re: account balance");
        }

// ArrayList<Person> getOwners()    

    
    if(str.contains("owner") )
        correct++;
    else{
        wrong++;
        p2("toString() incorrectly formatted, re: Account Owners");
        }

    ArrayList<Person> jamesAcctOwners = jamesAcct.getOwners();
    for(Person p : jamesAcctOwners){
        String strName = p.getName().toLowerCase();
    if(str.contains(strName) )
        correct++;
    else{
        wrong++;
        p2("toString() incorrectly formatted, re: Account Owners");
        if(verbose)
                p2("\t\t " + str + "\n \t\t\t Missing " + strName);
        }
    }//end of for-each


    if(str.contains("interest rate") )
        correct++;
    else{
        wrong++;
        p2("toString() incorrectly formatted, re: interest rate ");
        }
    
    if(str.contains(jamesAcct.getInterestRate() + "") )
        correct++;
    else{
        wrong++;
        p2("toString() incorrectly formatted, re: interest rate ");
        }




    Person jorge = new Person("jorge", 17) ;
    CertificateOfDeposit cd_foo = new CertificateOfDeposit(jorge, 500);
    cd_foo.withdraw(100, true);
    double jorgesMoney = cd_foo.getCurrentBalance();
    if(jorgesMoney == 200 )
        correct++;
    else{
        wrong++;
        if( jorgesMoney == 400)
            p2("You did not apply the EARLY_WITHDRAW_PENALTY for a CD's early withdrawal");
        else
            p2("Certificate of Deposit has wrong balance after early withdrawal");

    }


Account sb = new SavingsAccount( jorge, 100 );
Account sb2 = new SavingsAccount( joe, 100);
if( sb2.comparesTo(sb) == 1)
	correct++ ;
else
	{
	wrong++;
	p2("Account's comparesTo not implemented correctly");
	}


SavingsAccount sb33 = new SavingsAccount( jorge, 100 );

sb33.updateInterestRate(3.3);
if( sb33.getInterestRate()== 3.3)
	correct++;
else
{
	wrong++;
	p2("Savings account error involving interestRate");
	p2("\t either getInterestRate() or , more likely, updateInterestRate() is wrong ");

}


double ball_yr1 = sb33.projectBalance(1);
if( Math.abs(ball_yr1 - 103.350372874721)< 0.000001)
	correct++ ;
else
	{
	wrong++;
	p2("SavingAccount's projectBalance() incorrect");
	}


	p2("********************************************************************") ;
	p2("********************************************************************") ;
	p2("                       SCORE  ") ;
	p2("********************************************************************") ;
	p2("********************************************************************") ;
	p2("********************************************************************") ;

    p2("-------------------------------");
    p2("Correct :  " + correct);    
    p2("Wrong   :  " + wrong);    
    
    }


void p2(String s){
    System.out.println(s);
}
void p2(int s){
    System.out.println(s);
}
void p2(boolean s){
    System.out.println(s);
}
    


}
 
Tester.java

When you are done, you can begin the Bank project .

SuperClasses are Great II

How can we improve our current class structure?right_triangle_rectangle

 

 

 

 

 

 

 

We are going to create a second “Generation” of classes and will denote this change by appending a ‘2’ to the names of all classes in this “generation”

right_triangle_extends_polygon

 

Class: Polygon2 (superclass of Triangle2, Rectangle2)  Polygon2download-bttn

 

Constructor 

public Polygon2(int _col, double _width, double _height, int _sides)

instance Variables

  • private int color;
  • private int numSides
  • protected double width;
  • protected double height

Methods

  • public int getColor()
  • public double getWidth()
  • public double getHeight()

Class: Rectangle2 extends Polygon2  Rectangle2download-bttn

instance Variables

None needed (see superclass)

Accesor Methods //override each of the superclass

  • public double getArea(); //returns the area of the triangle

Class: RightTriangle2 extends Polygon2  RightTriangle2download-bttn

instance Variables

None needed (see superclass)

Accesor Methods //override each of the superclass

  • public double getArea(); //returns the area of the triangle
  • public double getHypotenuse()

InteractiveMath2   InteractiveMath2download-bttn

 

Next: What is inherited?