Category Archives: Computer Science

Bank Class

Bank Class

You have a lot of flexibility in creating this class, but here is what it should be able to do

Functionality that you *must* implement.

It’s up to you to decide how to implement the functionality below. You will only lose credit if your methods clearly make no sense, have bad variable names/method names.

  • add an Account  (of any type)
  • remove an account by
    • account id
    • owner (a Person object)

The functionality above ^^ can be implemented in any efficient way that makes sense, but it must be implemented. I am leaving that part up to you!


  • Some Specific Required Methods
    • public ArrayList<Person>  topAccountOwners(double cutoff)
      • this method returns an ArrayList of the owners whose accounts have at least cutoff  amount of balance
    • public void nightlyUpdate()
      • this runs through the accounts and if account is a SavingsAccount , then it calls that object’s recordDailyBalance()  method (You are going to have to use instanceOf  and then cast those  accounts to a  SavingsAccount )
    • public  Account topBalance()   ; returns the Account  object with the greatest balance
    • public  Account[] allWithinRange(double min, double max) returns an array of Accounts whose balances range from min  to max , inclusive
    • public  boolean transfer( double amount, int accountIdFrom , int accountIdTo) ;  this method transfers  money from the one account to the other. If the accountIdFrom  does not have enough $$, this method returns false.
    • public  void monthlyUpdate()
      • this runs through the accounts and if
      • account is a SavingsAccount , then it calls that object’s updateInterestPayment() method
    • ** extra credit ArrayList<Account> sortByAmount()  
      •   this method returns an arraylist of Accounts sorted by amount in the account

 

account_with_bank_no_labels

 

The Case for Abstract Classes and Methods

shape_abstract_class

 

Shape

download-bttn Shape Class

Constructor 

  • public Shape( int _col)

instance Variables

  • protected int color

Accesor Methods

  • public abstract double getArea(); //returns the area of the triangle
  • public int getColor()
  • public void render()  { System.out.println(“rendering shape” ) ; }

 

 


Now, let’s refactor our class relationships to represent our new Iheritance Tree

  1. refactor all subclasses to reflect new class hierarchy
  2. Update our new InteractiveMath class –InteractiveMath3

Circle Class

Create the following class

Circle

download-bttnCircle
Constructor 

  • public Circle( double _radius, int _col)

instance Variables

  • double radius
  • int color

Accesor Methods

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

What should Circle Extend?

circle_should_extend_what

Answer!

Constructors And Inheritance

What relationships exist between super and sub classes?

 

  • How can we use superclasses to improve ourInteractiveMath2 code?
    • To be implemented in  computeNetArea() method
    • How can an element in the Polygon2 ‘ list that  is a RightTriangle2 call the getHypotenuse() method?
      • To be implemented in the new method void printDetails() which should , among other , things print the hypotenuse length for any RightTriangle2’s?
  • What is Inherited by subclasses?
    • Constructors?
    • instance variables
    • static variables?

 Next: What if we want to add a Circle Class

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?

isLeapYear assignment

Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100; the centurial years that are exactly divisible by 400 are still leap years. For example, the year 1900 was not a leap year; the year 2000 was a leap year

 

 Call return value
 isLeapYear(100)  false
 isLeapYear(4)  true
 isLeapYear(104)  true
 isLeapYear(400)  true
 isLeapYear(800)  true
 isLeapYear(5)  false
 isLeapYear(803)  false

 

 

Seconds Since Birthdate

I . write bool isLeapYear( int year) : returns true or false depending on whether or not input is a leap year.

 

II. write a function called int secondsSince( int usersBYear, int usersBmonth, int usersBDay)  .

This function should return the number of seconds since that bithdate (year, month, day)

III.  In Main: use cout and cin to ask user for their bithdate  and then display how many seconds since that person’s bithdate

 

IV.  Determine how many seconds have occurred since 0/0/0 .

 

download-bttn Starting Code

PlayList Project [ArrayList]

A PlayList project will be based on 3 Classes

  • Artist
  • Song
  • PlayList

The Artist class will store core information about an artist.

The Song class will store basic information about a song.

The PlayList class will manage a list of artists and their ratings.

Tester files:

  • Artist and Song tester file SongArtistTester.v0  – run this after you have completed the Song and Artist classes and before PlayList. This way, you’ll know that you have correctly done the the foundation classes before moving onto PlayList
  • Some things about grading.
    • do not use any external libraries aside from the ArrayList
    • use proper naming conventions for instance variables, for methods and static methods
    • make sure that you employ code re-use. (do not copy and paste code, but use methods that you have already written)

Artist

  • Constructor(s) :

    • public Artist(String name)
  • Instance Variables
    • private String artistName ;
    • private ArrayList<Song>  songs  ; – an array storing the songs of this artist
  • Methods
    • public void addSong(Song song) . Create a song object (see above) and add it to the arraylist. Here’s the first line.
    • public String toString()
    • public boolean equals(Artist other)  //returns true  if the names (only) are the same
    • public ArrayList<Song> getSongs()
    • public String getName()

Example of instantiating an Artist object and calling one of its methods:


Song

  • Constructor(s):
    • public Song( Artist _artist, String _name)
  • Instance Variables
    • private Artist artist
    • private String name
  • Methods
    • public String getName()
    • public Artist getArtist()
    • public boolean equals(Song other) //returns true  if both the song objects have the same artist and name.
    • public String toString()

Example of instantiating a Song object :


PlayList

  • Static Variable
    • public static final int MAX_NUMBER_SONGS= 6 ;

  • Instance Variables

    • private String listName  ; This is the ‘name’ of your playList
    • private ArrayList<Song> songs  ;
    • private ArrayList<Integer> stars   ;//how many stars each song has
    • Note: songs and stars are parallel ArrayLists
  • 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 ArrayList<Song> getSongs()  // returns the songs
    • 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 parameter artist
    • public ArrayList<Artist> getArtist(String songName) // returns an ArrayList of all Artists associated with the String songName (This could be multiple musicians. Cover songs etc..)
    • private int indexOf(Song someSong)  //
    • public String toString()  //returns an appropriate String representation of the PlayList  . Here is an example of the toString() value for a  PlayList I created.
    • public String getName() // @returns the listName of the PlayList
    • public ArrayList<Integer> getStars()  //returns the stars  ArrayList

    Mutator Methods

    • public void swap(Song song1 ,  Song song2, ) // switches positions of these two (maintain parallelism!)
    • public boolean add(Song _song , int _stars)
      //adds data if number of song is less than MAX_NUMBER_SONGS
    • public void removeSong(Song song) /removes all occurrences of song . There could be multiple instances of song. Maybe someone really likes a particular song and has it several times in one list. (Hint : Do not loop forwards)
    • 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 or equal to cutOff

The method’s below are extra credit. If you figure out how to do them, you must also meet with me after school about the methods. To receive the extra credit, be prepared for a mini-quiz on how they work.  Be prepared for me to ask about your solution and how changing certain parts of your code would affect your solution. This meeting must happen on the Monday or Wednesday following the deadline.

 

  • ** 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
    • To do this , you should use a sorting algorithm. I suggest, Selection Sort (link). As this both intuitive and on the AP.
  • ** public PlayList shuffle()/ /this returns a new PlayList in which all of the songs have been reordered randomly

When you’re done this, begin exploring different sorting algorithms with this online sorting detective :

 

https://labs.penjee.com/sort-detective/

 

sort-detective

 

 

Alice Projects (if-else and loops)

 

  • Packets #12 -14
  • 1)Kick Ball Create a world with your choice of a ball from the Sports collection and your choice of person from the People collection. Position the ball in front of one of the person’s feet. When you play the world, it should ask the user how far the person should kick the ball. Then the person object should move one of its legs in a kicking motion, and appear to kick the ball. The ball should move the distance specified by the user.
  • 2) Miles Per Gallon: Create a world in which the user is asked for the number of gallons of fuel his or her car can hold, and the number of miles that he or she can drive on a full tank. Use variables to hold these values. You should also have a variable to hold the car’s miles-per-gallon (MPG). Calculate the MPG with the following formula

    The world should have a person and a car. In the initial setup the car should approach the camera and the car should drive into view and stop in front of the camera. The person should then say a message indicating the car’s MPG, as calculated from the data entered by the user. Then, the car should drive away, to a position of the world
  • 3) Fahrenheit to Centigrade : The following formula is used to convert Fahrenheit temperature to Centigrade temperature:
      C = (5/9) * (F − 32)

    In the formula, C is the Centigrade temperature and F is the Fahrenheit temperature. Create a world in which the user is asked to enter a Fahrenheit temperature. Use a math expression to convert the temperature to Centigrade and store the converted temperature in a variable. Use a character from the People collection to say the centigrade temperature.

  • 4) Circle’s Area and Circumference: Create a world with your choice of person from the People collection. When you play the world, it should ask the user how for the radius of a circle. (This value should be stored in a variable ). The person should then say the area and the circumference of the circle.(circumference formula , area of a circle) (For an extra point do the same thing with a “Sphere”. Ask the user for the radius and calculate the .
  • ** Project 5 )For those shooting for an A. Look up the formulas for the volume and surface area of a cylinder . Ask the user for the height of the cylinder and the radius, which should be stored in variables. Then calculate the surface area and volume of the cylinder . See if there is a cylinder shape in the gallery to use as a visual aid.

Part II

  • Complete Packets #15, 16
  • Exercise 1 GumdropFish Modification: Modify the GumdropFish world that you created in Tutorial 4-2 so that the fish eats both of the gumdrops. First it should eat the gumdrop that is closest (as it currently does) , and then it should move to the other gumdrop and eat it. Both gumdrops should have their magical effect on the fish: the red gumdrop should make the fish twice its current size, and the yellow gumdrop should make the fish half its current size.
  • Exercise 2 FanLoop Modification: Modify the FanLoop world on the Student CD so it asks the user for the number of times the fan blades should rotate. Use this value in the Loop statement to control the number of times the roll method is called.
  • Exercise 3 Sea Plane Loop-the-Loop : Create a world with a sea plane (from the Vehicles collection).Create an infinite loop that causes the sea plane to do a circular loop the loop. Adjust the style and duration editing tags to make the animation fast, and as smooth as possible.
  • Exercise 4 Centigrade to Fahrenheit Modification: Modify the Fahrenheit to centigrade project as follows. At the start, ask the user how many temperatures they want to convert. Then use a loop to do that many conversions
  • Exercise 5 Miles Per Gallon Modification: Modify the miles per gallon project in the same way as the prior exercise. Ask the user how many miles per gallons they want to convert, and then use a loop to repeat the miles per gallon calculations.