Tag Archives: OOP

Class Roster Array Version [Java] Assignment

Class Roster: This class will implement the functionality of all roster for school. It will , in essence, manage an Array of Student objects. Each roster will store a default of 10 Students

  • “global” Instance Variables
    • private Student myStudents   : an array storing Student Objects
    • private String className  (a name to represent a given roster like “Ap CS”)
    • public int period //during which period of the day does this roster meet
  • a default constructor should initialize the Array to store 20 strings
    a single parameter constructor that takes an Array <String>
    Both constructors should initialize the instance variables
  • Methods
    • Accessors
      • private int indexOf(Student st) //@returns index of Student St or -1
      • public boolean containsStudent(Student studentName )/ /@returns true if studentName is in roster .
      • public boolean equals(ClassRoster other) //@ returns whether or not rosters are equal. Rosters are equal if identical students are in identical order in the lists
    • Mutators:

public void addStudent(String studentName, int age) ;// adds student name and age to end of roster

. Hint: Make user of the containsStudent() method
public boolean removeStudent(int ssnId ) // removes student from roster based on id. Make sure that you maintain the integrity of the parallel ArrayLists.

public boolean removeStudent(String name) //removes student based on name. Make sure that you maintain the integrity of the parallel ArrayLists.

public  boolean removeStudent( Student st) //removes student st. Make sure that you maintain the integrity of the parallel ArrayLists.

Student Object (OOP Java)

Student Class

A school district decided to write a program to help keep track of various parts of the school.

It has been decided to store relevant information about Students in a Student class. Each Student will have an array of Strings to store the names of his or her teachers.

private instance variables

 

Part 1

* Construct the Java statement to declare the array called

teachersNames to store the String names of the student’s teachers

Part 2

  • write a default constructor
  • construct a method called  addTeacher( String name) that adds String name to the  teachersNames  array
    • to do this let’s create a private method  private String[] addStr( String[] input, String val) that adds value to the end of the array and returns it. [redact]Solution[/redact]
  • construct hasTeacher(String name)  that returns true if name is in the teachersName array
  • construct a method removeTeacher(String name) that removes the   String name from the  teachersNames  array.
  • construct a method the line of code needed in the setGpa(double to) method of the Student Class.
  • construct a method boolean setTeacher (String name, int index) .   This method should return true if index is valid in the array and false if  index >= teachersName.length

 

Next: The runner class

Playlist Project [Array]

A PlayList project will be based on Three Classes

The Artist class will store core information about an artist

The Song class will store basic information about a music song

The PlayList class will manage lists of songs and artists


 

Artist

  • Constructor(s) :
    public Artist( String name) { //missing code }

 

  • Instance Variables (“global” variables)

 

Methods

 


 

Song

Constructor(s):

Instance Variables

example of how to get current milliseconds as a long

Method

 


 

Artist

Song

PlayList


 

PlayList

  • Instance Variables
    • private String listName : This is the ‘name’ of your playList
    • private Song[] songs;
    • private  int[] stars ; //how many stars each song has between 0 and 5 inclusive.
    • Note: songs and stars are parallel Arrays
  • Constructor
    • public PlayList(String name) : There should be only 1 constructor that takes a parameter representing the name of the playList
  • Accessor Methods
    • public double averageRating() // returns the average star rating for the list
    • public double averageRating(Artist artist)  // returns the mean star rating associated with artist
    • public Song[] getSongs(Artist artist) // returns an array populated by the songs of the parameter artist
    • public Song[] getSongs() // returns all the songs in the list

    Mutator Methods

    • public void swap(Song song1 ,  Song song2 )  // switches positions of these two (maintain parallelism!)
    • public void  add(Song song , int stars)
    • public void removeSong(Song song, String artist )  //removes song associated with artist
      • Note: Be careful here. You are allowed to add the same song and artist. Duplicates are allowed.
    • public void removeArtist(Artist artist ) //removes all elements associated with artist
    • public void removeLowStars(int cutOff) //removes all elements associated with a star rating less than cutOff
    •  ** public PlayList sortByDate() //this returns a rearranged PlayList based on each Song’s date
    • ** public PlayList sortByRating() //this returns a rearranged playlist so that the 5 starred elements are the first group in the list, 4 stars second …1 stars, last
    • ** public PlayList shuffle() //this returns a new PlayList in which all of the songs have been reordered randomly.

Artist

Song

PlayList

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 .

Super Classes Are Great I

 

Question: What limitations seem to exist with our use of classes?

 

I. Implement all Methods of the Triangle and Rectangle methods below

right_triangle_rectangle

 

Class: Rectangle  download-bttnRectangle

Constructor 

  • public Rectangle ( int  _col,  double  _width,  double _height)

instance Variables

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

Accessor Methods

  • public double getArea(); //returns the area of the rectangle
  • public int getColor()

 


Class: RightTriangle  download-bttnRightTriangle

Constructor 

  • public RightTriangle( int _col,  double  _width,  double _height)

instance Variables

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

Accessor Methods

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

Class: InteractiveMath

download-bttn InteractiveMath-Arraylists (USE THIS ONE)

instance Variables

  • ArrayList<Rectangle> rectangles;
  • ArrayList<RightTriangle> triangles;

Accesor Methods

  • public double computeNetArea(){ //@ returns the area of the rectangles and triangles

 


Next  : Super Classes are great 2


Then  : constructors and inheritance.


after that : What is “Inherited” by Subclasses?

 

 

interactiveMath_arrays