Category Archives: Java

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

 

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

 

 

Class Roster Java Assignment

Class Roster: This class will implement the functionality of all roster for school. It will , in essence, manage an ArrayList of Student objects.

Client file:   tester file

  • Class or static variables

    • representing the maximum number of students allowed on the roster
  • Instance Variables

    • : an ArrayList storing Student Objects

//during which period of the day does this roster meet

Constructors

  • a default constructor should initialize the list to empty strings
  • single parameter constructor with the period as a parameter
    Both constructors should initialize the instance variables

Methods

  • Accessors
    • private int indexOf(Student st) //@returns index of Student St or -1
    • public boolean contains(Student st) //@returns true if studentName is in roster
    • public boolean contains(int ssnId)  //@returns true if a student in the list has that SSN
    • public int getPeriod() // returns period
    • public Student retrieveBySSNId(int ssnId ) //@ returns Student associated with id. This should return null if the student does not exist.
    • public boolean equals(ClassRoster other) //@ returns whether or not rosters are equal
    • public ArrayList<Student> getStudents() //@returns the ArrayList of all students in the roster
    • public String toString()

Mutators:

  • public boolean addStudent( Student st )  ;//if the size of the arraylist is less than MAX_NUM, add the student and return true; otherwise, return false and do not add student.
  • public boolean addStudent(String studentName, int age) ;//adds student name and age to end of roster
    • Make sure that the total number of students does not exceed MAX_NUM.
  • public Student removeStudent(int ssnId ) // removes student from roster based on id.
  • public Student removeStudent(String name)  //removes student based on name.
  • public  Student removeStudent( Student st) //removes student st.

Student Class

This class will be used in our Class Roster assignment .

Here is a client  test file . This tester file should not be   in the same class/file as Student . Instead. just put the tester into BlueJ into class called StudentRunner , within  the same BlueJ project,  and run the client file.

Instance variables

  • private String name
  • private int age
  • private int socialSecurityNum  (  How can we guarantee unique social security  numbers? )

Constructors

  • default
    • public Student()   .
  • public Student( String _name)
  • public Student (String _name,  int _age)

Accessors

  • public int getSSN()
  • public int getAge()
  • public String getName()
  • public boolean equals(Student other)
  • public String toString()

Mutators

  • public void setAge( int  _age)
  • public void setName( String to)

ArrayList 1 Excercises

BlueJ users. Read this about how to use ArrayLists as parameters. Or consider using Eclipse if this is too much of a hassle.

ArrayList<Integer> factors(int num)

Description: This method returns an ArrayList populated with the factors of num

Method Call return value/output
factors(5) {1,5}
factors(10) {1,2,5,10}

int sum(ArrayList<Integer> nums)

Description: This method returns the sum of all elements in the list

Method Call return value/output
sum({1,5}) 6
sum( { 3,4, 2 }  ) 9

void printReverse(ArrayList<String> strs)

Description: This method prints all elements in reverse order

Method Call return value/output
printReverse({“a”,”b”}) “b”
“a”
printReverse( “xu”, “t”) “t”
“xu”

double mean(ArrayList<Integer> nums)

Description: This method returns the arithmetic mean of all elements in the list

Method Call return value/output
mean({1,5}) 3
mean( {3,4, 2 } ) 4.5

void printEvens(ArrayList<Integer> nums)

Description: This method prints out all even numbers

Method Call return value/output
printEvens({1,5 , 6}) 6
printEvens( {3,4, 2 }  ) 4 , 2

ArrayList<Double> everyOtherPi(ArrayList<Double> nums )

Description: This method returns a version of the input ArrayList with every other value changed to Math.PI

Do NOT make a new ArrayList in this method

Method Call return value/output
everyOtherPi ( {1,8,5,0, 7} ) {1, 3.1415 , 5 , 3.1415 , 7 , 3.1415 }
everyOtherPi({0,4,3,5} ) {0, 3.1415 ,  3 , 3.1415 }

boolean isIdentical(ArrayList<String> strs1 , ArrayList<String> strs2)

Description: This method returns true if each element in the two ArrayLists is the same

Method Call return value/output
isIdentical({“ab”, “a”} , { “x”, “a”} ) false
isIdentical({“ab”, “a”} , { “ab”, “a”} ) true
isIdentical({ “xy”} , { “XY”} ) false

int largest(ArrayList<Integer> nums)

Description: This method returns the largest element in nums

Method Call return value/output
largest({1,5 , 6}) 6
largest ({3,4, 2 }  ) 4

ArrayList<Integer>removeVal(ArrayList<Integer> nums, int val)

Description:This method returns an ArrayList with all instances of val removed

Do NOT make a new ArrayList in this method

Method Call return value/output
 removeVal({1,5 , 6}, 5 ) {1, 6 }
removeVal  ( {3,3,3,4, 2} , 3 ) {4,2}

 

 

TO do :

PrimesFactory

2 D Arrays in Java Assignments

Add the following Methods to a class called ArrayFun2D

public void print(int[][] arr)

Description: This method prints each element in the array. This will be a useful method when you are debugging your code and want to test it out to see if it works.

Method Call return value
print({{1,2} , {3,4}, { 5, 6 } } ) 1   2
3  4
5   6

public int sum(int[][] arr)

Description: This method returns the sum of all elements in the array

Method Call return value
sum({{1,2} , {3,4}, { 5, 6 } } ) 21 ( ie 1+2+3+4+5+6)

public String concat(String[][] strs)

Description: This method returns the concatenation of all the elements in the Array

Method Call return value
concat({{“a”,”xc” }, {“t”, “zoo”}, { “jjkj” } } ) “axctzzoojjkj”

public double mean( int[][] arr)

Description: This method returns the arithmetic mean of the array. Make sure you double check that you are correctly returning results that include decimal values .

Method Call return value
mean({{2,8} , {4 , 7} } )  5.25 ie (2+8+4+7)/4

public void printRow(int[][] arr, int row)

Description: This method prints all elements in rowThis can be (and should be) done with a single loop.

Method Call return value
printRow({{1,2} , {3,4}, { 5, 6 } } , 1 ) 3, 4
printRow( { 5 , 6} , {7, 12, 13 , 5 }, { 5, 6 ,0} } , 2 ) 5 , 6, 0

public void printCol(int[][] arr, int col)

Description: This method prints all elements in col

Method Call return value
printCol({{1,2} , {3, 4}, { 5, 6 } } , 1 ) 2
4
6
printCol( { 5 , 6} , {7, 12, 13 , 5 }, { 12, 6 ,0} } , 0 ) 5
7
12
printCol(    {12, 13 , 5 }, { 6, 2, 13 ,11}  , {1,2 } } , 2 ) 5
13

public int maxVal_inRow(int[][] arr, int row)

Description: This method returns the value of the largest number in the given row

Method Call return value
maxVal_inRow({{1,2} , {3,4}, { 5, 6 } } , 1 ) 4
maxVal_inRow ({   { 5 , 6} , {7, 12, 13 , 5 }, { 5, 6 ,0} } , 2 ) 6

public int maxVal_inCol(int[][] arr, int col)

Description: This method returns the value of the largest number in the given col

Method Call return value
maxVal_inCol({{1,2} , {3,4}, { 5, 6 } } , 0 ) 5
maxVal_inCol({{1,-2} , {3,-4}, { 5, -5 } } , 1 ) -2

public int[][] changeValues(int[][] table, int val)

Description:This method returns the array with all elements set toval

changeValues(table, 5)

Original Array

1 2
3 4
5 6
Returned Array

5 5
5 5
5 5

public void print_colMajor(int[][] arr)

Description: This method prints each element in the array – using column major order

Method Call return value
print({{1,2} , {3,4}, { 5, 6 } } ) 1   3   5
2  4    6

 

public int[][] removeVals(int[][] table, int val)

Description: This method returns a version of the 2-d array where val has been removed from all elements

removeValues(table, 5)

Original Array

{1 , 5}
{3, 4}
{5, 6}
Returned Array

{1}
{3, 4}
{6}

 

int[] twoD_to1D(int[][] arr)

Description: This method takes an input array that is in 2 dimensions  and  creates a 1 d array . Assume that the array is rectangular (not jagged).

Method Call return value
twoD_to1D ( {{1,2} , {3,4}, { 5, 6 } } ) { 1 , 2 ,  3 ,  4 , 5 ,  6 }

Matrices

int[][] add (int[][] matr1, int[][] matr2)

Description: This method returns the sum of matr1 and matr2

how to add matrices


 

** int[][] multiply(int[][] matr1, int[][] matr2)

Description: This method returns the product of matr1 and matr2

how to multiply matrices

**public int[][] invertValues(int[][] matr)

Description: This method returns the paramater with its values ‘inverted’

Original Array

1 2
3 4
5 6
Returned Array

6 5
4 3
2 1

Extra Credit Java Arrays Question

Extra Credit (GOOD LUCK!)

 

Note first try addition , also worth some (though less) extra credit.

** int[] multiply(int[] num1, int[] num2, int base) throws ArithmeticException

@precondition 1 < base < 11
@precondition num1.length = 5 and num2.length = 5
@postcondition: the returned array has 5 elements representing the product or an ArithmeticException is thrown

Description: This method attempts to replicate multiplication. Both num1 and num2 represent five digit numbers. Each element in the array stores one of the digits. For instance, the number 143 would be represented as {0,0,1,4,3 }. Numbers can be in any base between 2 and 10 inclusive , and the number 101102 in binary would appear in an arrays as : {1, 0, 1 , 1, 0 } . Let’s assume the numbers are positive. You should return an array representing the digits of the product of num1 and num2. If the number of digits in the product exceeds the maximum number of digits (5) , you should throw an arithmetic exception as shown in the code below:

Note: You may not use any kind of helper or utility methods that are built into pre-defined Java classes for converting numbers between bases. Only use techniques taught in this class.

Method Call return value/output
multiply ( {0,0,0 , 4,2},{0,0,0,5,1}, 10)   {0 , 2 ,  1 ,  4 ,  2}    (42 *51= 2142)
multiply ( {0,0,0, 3,1} , { 0 ,0,0,2,4}, 10) {0 , 0 ,  7 , 4 ,  4}    (31 *24= 744)
multiply ( {6,5,1, 3,1} , { 0 ,0,0,2,4}, 10) throw an ArithmeticException

Tool for checking work

Use programmers calc to check your work. This is an awesome 64 calculator and you can multiply in binary, decimal or octal to help you see if you did your work correctly.

Luhn Check Assignment

Luhn Check

It is possible to tell if a number could be a valid credit card. Credit cards numbers can be validated against an algorithm known as a Luhn.  Read this first.

Luhn Number Generator

 

http://www.datagenetics.com/blog/july42013/index.html

Counting from the check digit, which is the rightmost, and moving left, double the value of every second digit.

Sum the digits of the products together with the undoubled digits from the original number.

If the total ends in 0 (put another way, if the total modulo 10 is congruent to 0), then the number is valid according to the Luhn formula; else it is not valid.

 

from : http://www.impuls-imaging.com/wp-content/uploads/2013/07/luhn_algorithm.png

from : http://www.impuls-imaging.com/wp-content/uploads/2013/07/luhn_algorithm.png

Image from http://www.impuls-imaging.com/wp-content/uploads/2013/07/luhn_algorithm.png

Mod 10+5 Variant Some credit cards use the “Mod 10 plus 5” variant to extend the space of valid card numbers.[citation needed] In this variant, if the sum ends in 0 or 5, the number is considered valid.

from http://www.moneybluebook.com/imagesvr_ce/mbb/luhn-amex-calculation.jpg

from http://www.moneybluebook.com/imagesvr_ce/mbb/luhn-amex-calculation.jpg

from http://www.moneybluebook.com/imagesvr_ce/mbb/luhn-amex-calculation.jpg

 

 

A more extensive analysis with good images and an online Luhn Checker  (currently blocked by Harrison network filter)