Category Archives: Java

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

Array Fun 2

Java Assignment

Create a Class called ArrayFun2  that has the following methods Write the body for the methods described below.

 

Description: This method creates an array that is filled with all of the digits of nums.

Method Call return value/output
digitsToArray( 523 ) {3, 2, 5}
digitsToArray(1267 ) { 7 , 6 , 2,  1 }

public boolean allFactorsOfSum(int[] nums)

Description: This method returns true if each element ofnums is a factor of the sum of nums.

Method Call return value/output
allFactorsOfSum( {6,1,2,3} ) true (because all of the elements are factors of the sum which is12)
allFactorsOfSum( 1,4,7) false (because 7 is not a factor of the sum of this array which is 12)

public String[] doubleArr(String[] strs)

Description: This method returns a new version of strs with each element appearing twice.

Method Call return value/output
doubleArr( {“a”,”b”,”c”} ) {“a”,”a”,”b”,”b”, “c” , “c”}
doubleArr( {“math”,”ware”,”house”,”.com” }) {“math”,”math”,”ware”,”ware”,”house”,”house”,”.com”, “.com”}

public boolean isThere(int[] nums, int num)

Description: This method returns true if num is an element nums.

Method Call return value/output
isThere( {6,1,2,3}, 6) true
isThere( {6,1,2,3}, 5 ) false

public int indexOf(int[] nums, int num)

Description: This method returns the index value of the first appearance of num or -1 if num is not an element of nums .

Method Call return value/output
indexOf( {6,4 ,7,3, 4 }, 4) 1
indexOf( {6,4 7 ,3,2,7}, 7) 2
indexOf( {6,4 ,2,3}, 22) -1

public int lastIndexOf(int[] nums, int num)

Description: This method returns the index value of the last appearance of num or -1 if num is not an element of nums .

Method Call return value/output
lastIndexOf( {6, 4 ,7 ,3, 11, ,4}, 4) 5
lastIndexOf( {7, 6,4 , 7 ,3}, 7) 3
lastIndexOf( {6,4 ,2,3}, 22) -1

public boolean isIncreasing(double[] nums)

Description: This method returns true if each element in nums is greater than the element to its left.

Method Call return value/output
isIncreasing( {1,2,3,4 }) true
isIncreasing( {1,0 ,3,4 }) false
isIncreasing( {1,1, 2,3,4 }) false

public int largestSpan(int[] nums)

Description: This method returns the largest span of consecutive increasing numbers

Method Call return value/output
largestSpan( {4, 3, 1, 2, 3 , 1} ) 3
largestSpan( {4  , 3,  1 , 12 , 31 , 44 , 52 , 1} ) 5
largestSpan( {9, 7, 8 , 12,4, 3, 0, 4 , 1) 3
largestSpan( {1, 0, 4, 5 , 3,  2, 8 , 9, 10, 12, 4, 3,  1 }) 5

** int[] invert(int[] nums)

Description: This method ‘inverts’ an array by spliting the array in halves and ‘inverting’ each half. See sample calls to understand.

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

** int[] shiftByN(int[] nums, int delta)

Description: This method returns the array with all digits shifted by delta . Any digits that are circulated off the end of the array should be returned to the other side. Note: delta could be positive or negative. Please keep in mind that Math.abs(delta) > nums.length could be possible 😉

Method Call return value/output
shiftByN( {5 , 21, 13,4 } 1) { 4 , 5 , 21, 13 }
shiftByN( {5 , 21, 13, 4 , 11} 2) { 4 , 11 , 5 , 21, 13}
shiftByN( {5 , 21, 13, 4 } -1) { 21, 13, 4 , 5}
shiftByN( {5 , 21, 13, 4 ,7 } -2) { 13, 4 ,7 , 5 , 21}
** int[] add(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 sum or an ArithmeticException is thrown

Description: This method attempts to replicate addition. Consider both num1 and num2 represent the five digits of a number. 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 sum of num1 and num2. If the number of digits in the sum 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
add( {0,0,0 ,4,2},{0,0,0,5,1}, 10) {0, 0, 0, 9, 3} ie (42 + 51 = 93)
add( {0, 0, 0 ,7,2},{0,0,0,5,1}, 10) {0, 0 , 1 , 2, 3} ie (72 + 51 = 123)
add( {0, 0 , 0 , 1 , 1}, { 0 , 0 , 0 , 1 }, 2) {0, 0 , 1 , 0 , 0} ie ( 112 + 12= 1002 )

Java String Project Bases and Decimals

Create a class called BaseMaster (spelled exactly like this)

 

//helper functions

the isNumeric() method returns true if every digit is an integer . It also allows for a single ‘.’ to represent a decimal point.

 

 

example call return value
isNumeric("3.1") true
isNumeric("3.1.1") false
isNumeric("3a") true (assume base 16)
 isNumeric("3D")  true (assume base 16)

To get A+, you need to make base10toOtherBase() support bases 2-10 AND base 16

Online Computer Science Resources

Lynda.com Courses

 Binary Numbers

Web Developmemnt

Learning Java

  • Stanford’s Online Youtube Video set “Programming Methodology
  • Udacity’s  Intro to Java Class
  • self paced, and run by Cay Horstman a well known programming educator who, among other things, has worked with parts of the college board’s AP exam

    Syllabus

    Lesson 1: Introduction to Computers, Programming Languages, Algorithms, and the Java Programming Environment
    Lesson 2: Introduction to Classes and Objects
    Lesson 3: Graphics
    Lesson 4: Fundamental Data Types
    Lesson 5: Decisions
    Lesson 6: Iterations
    Lesson 7: Arrays, ArrayLists and Simple Array Algorithms
    Lesson 8: Methods (Parameter Passing, Instance vs. Static Methods)
    Lesson 9

  • edX – into to Java
    • not self paced
  • Syllabus
    Week 1: Introduction to computing systems from hardware, software and problem solving aspects
    Week 2: Basic data types, variables, assignment statements and expressions
    Week 3: Objects, classes and methods; scope rules, Java documentation
    Week 4: Boolean expressions, control structures
    Week 5: Loops
    Week 6: Arrays and multidimensional arrays
    Week 7: Character string and file I/O
    Week 8: Recursion
    Week 9: Abstract data type
    Week 10: Simple event-driven programming and wrap up

  • : Inheritance

  • j

 

Web programming

Array Fun 2 [Java]

public int[] digitsToArray(int nums)

Description: This method creates an array that is filled with all of the digits of nums.

Method Call return value/output
digitsToArray( 523 ) {5,2,3}
digitsToArray(1267 ) { 1 , 2 , 6 , 7}
public boolean allFactorsOfSum(int[] nums)

Description: This method returns true if each element of nums is a factor of the sum of nums.

Method Call return value/output
allFactorsOfSum( {6,1,2,3} ) true (because all of the elements are factors of the sum which is12)
allFactorsOfSum( {1,4,7 }) false (because 7 is not a factor of the sum of this array which is 12)
public String[] doubleArr(String[] strs)

Description: This method returns a new version of strs with each element appearing twice.

Method Call return value/output
doubleArr( {“a”,”b”,”c”} ) {“a”,”a”,”b”,”b”, “c” , “c”}
doubleArr( {“math”,”ware”,”house”,”.com” }) {“math”,”math”,”ware”,”ware”,”house”,”house”,”.com”, “.com”}
public boolean isThere(int[] nums, int num)

Description: This method returns true if num is an element nums.

Method Call return value/output
isThere( {6,1,2,3}, 6) true
isThere( {6,1,2,3}, 5 ) false
public int  indexOf5(int[] nums )

Description: This returns the index of the first occurrence element ‘5’ or -1 if 5 does not exist.

Method Call return value/output
indexOf5( { 2 , 3 , 5 , 4 } ) 2
indexOf5( { 2 , 3 , 5 , 4, 5  } ) 2
indexOf5( { 2 , 3 ,7  , 4, 3,   } ) -1

 

public int indexOf(int[] nums, int num)

Description: This method returns the index value of the first appearance of num or -1 if num is not an element of nums .

Method Call return value/output
indexOf( {6,4 ,7,3, 4 }, 4) 1
indexOf( {6,4 7 ,3,2,7}, 7) 2
indexOf( {6,4 ,2,3}, 22) -1
public int lastIndexOf(int[] nums, int num)

Description: This method returns the index value of the last appearance of num or -1 if num is not an element of nums .

Method Call return value/output
lastIndexOf( {6, 4 ,7 ,3, 11, ,4}, 4) 5
lastIndexOf( {7, 6,4 , 7 ,3}, 7) 3
lastIndexOf( {6,4 ,2,3}, 22) -1
public boolean isIncreasing(double[] nums)

Description: This method returns true if each element in nums is greater than the element to its left.

Method Call return value/output
isIncreasing( {1,2,3,4 }) true
isIncreasing( {1,0 ,3,4 }) false
isIncreasing( {1,1, 2,3,4 }) false
 isIncreasing( {-1, –1, -2, -3, -4 })  false
* public int largestSpan(int[] nums)

Description: This method returns the largest span of consecutive increasing numbers

Method Call return value/output
largestSpan( {4, 3, 1, 3, 6 , 1} ) 3
largestSpan( {4 3 1 , 12 , 31 , 44 , 52 , 1} ) 5
largestSpan( {1 , 7 8 , 12,4, 3, 0, 4 , 1) 3
** int[] invert(int[] nums)

Description: This method ‘inverts’ an array by spliting the array in halves and ‘inverting’ each half. See sample calls to understand.

Method Call return value/output
invert( {5 , 21, 5, 13,4 }) {21 , 5 , 5, 4,13 }
** int[] shiftByN(int[] nums, int delta)

Description: This method returns the array with all digits shifted by delta . Any digits that are circulated off the end of the array should be returned to the other side. Note: delta could be positive or negative. Please keep in mind that Math.abs(delta) > nums.length could be possible 😉

Method Call return value/output
shiftByN( {5 , 21, 13,4 } 1) { 4 , 5 , 21, 13 }
shiftByN( {5 , 21, 13, 4 , 11} 2) { 4 , 11 , 5 , 21, 13}
shiftByN( {5 , 21, 13, 4 } -1) { 21, 13, 4 , 5}
shiftByN( {5 , 21, 13, 4 ,7 } -2) { 13, 4 ,7 , 5 , 21}
*** int[] add(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 sum or an ArithmeticException is thrown

Description: This method attempts to replicate addition. Consider both num1 and num2 represent the five digits of a number. 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 sum of num1 and num2. If the number of digits in the sum 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
add( {0,0,0 ,4,2},{0,0,0,5,1}, 10) {0, 0, 0, 9, 3} ie (42 + 51 = 93)
add( {0, 0, 0 ,7,2},{0,0,0,5,1}, 10) {0, 0 , 1 , 2, 3} ie (72 + 51 = 123)
add( {0, 0 , 0 , 1 , 1}, { 0 , 0 , 0 , 1 }, 2) {0, 0 , 1 , 0 , 0} ie ( 112 + 12= 1002 )

Array Fun 1 [Java]

Array Fun 1

 

Create a Class called ArrayFun that has the following methods Write the body for the methods described below.

public int[] swapFirstLast(int[] nums)

Description: This method returns a new version of the array with the first and last elements ofnums swapped.

Method Call return value/output
swapFirstLast( {3, 2 ,5 } ) {5,2,3}
swapFirstLast( {7, 6 ,9 ,12} ) { 12 , 6 , 9, 7}

public String[] swapFirstMiddle(String[] strs)

Description: This method returns a new version of the array with the first and middle elements ofstrs swapped.

Method Call return value/output
swapFirstMiddle( {“a”,”b”,”c” } ) { “b”, “a”, “c”}
swapFirstMiddle( { “zoo”,”foo”, “xoo”} ) { “foo”,”zoo”, “xoo”}

Loops


public void printEveryOther(int[] nums)

Description: This method prints every other element of nums on new lines .

Method Call return value/output
printEveryOther( {1 , 2 , 3 , 4 } ) 1
3
printEveryOther( {13 , 42 , 33 , 44 , 52} ) 13
33
52

public int sum(int[] nums )

Description: This method returns the sum of nums..

Method Call return value/output
sum( { 2 , 8 }) 10 ie 2 + 8
sum( { 2 , 8 , 4 } ) 14 ie (2 + 8 + 4 )

public int sumOdds(int[] nums )

Description: This method returns the sum of all the odd element of nums.

Method Call return value/output
sumOdds( { 5 , 2, 4 , 6 , 7 } ) 12 ( ie 5 + 7 )
sumOdds( { 13 , 3, 2, 6 , 7 } ) 23
public double mean(int[] nums )

Description: This method returns the mean of nums. Pay close attention to the second sample call and make sure you get “5.25

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

public double largest(double[] nums )

Description: This method returns the element of nums with the greatest value. Make sure that you test out the second call and get ‘-2‘.

Method Call return value/output
largest( { 2.6 , 8.2, 5.2}) 8.2
largest( { -2,-11, -4} ) -2

public int sumEveryN(int[] nums, int n)

Description: This method returns the sum of every n elements of nums..

Method Call return value/output
sumEveryN( {1 , 2 , 3 , 4 }, 2 ) 4( ie 1 +3)
sumEveryN( {13 , 42, 15, 33 , 44 , 16 , 52} ,3) 98 ( ie 13 + 33+ 52)

*public int secondSmallest(int[] nums )

Description: This method returns the element of nums with the second smallest value.

Method Call return value/output
secondSmallest( { 2 , 18 , 22, 4 , 6 } ) 4
secondSmallest( { 3 , 7 , 15 , 1 ,101} ) 3

** boolean isPalindromic(int[] nums)

Description:This method returns true if the elements of nums are a palindrome..

Method Call return value/output
isPalindromic(( { 5 , 2, 7 , 2 , 5} ) true
isPalindromic( { 5 , 2, 7 , 3 , 5} )) false
isPalindromic(( { 1 , 2, 1} ) true

 


 The question below is extra credit .
** int[] add(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 sum or an ArithmeticException is thrown

Description: This method attempts to replicate addition. Consider both num1 and num2 represent the five digits of a number. 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 sum of num1 and num2.  You may not do any math besides addition. You may not use any external libraries for any math or base conversions.   If the number of digits in the sum 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.  What you have to do is reproduce the additional algorithm and find a way to carry digits , programmatically.

Method Call return value/output
add( {0,0,0 ,4,2},{0,0,0,5,1}, 10) {0, 0, 0, 9, 3} ie (42 + 51 = 93)
add( {0, 0, 0 ,7,2},{0,0,0,5,1}, 10) {0, 0 , 1 , 2, 3} ie (72 + 51 = 123)
add( {0, 0 , 0 , 1 , 1}, { 0 , 0 , 0 , 1 }, 2) {0, 0 , 1 , 0 , 0} ie ( 112 + 12= 1002 )

Java String Loops 2

public int countF(String str)

Description: This method returns the number of times that the letter ‘f’ occurs in str.

Method Call return value/output
countF(“abcdef”) 1
countF(“abcdfef”) 2
countF(“fff”) 3
countF(“xxx”) 0

 

public boolean has2Fs(String str)

Description: This method returns true if str has exactly two occurrences of the letter ‘f’ in it.

Method Call return value/output
has2Fs(“foo”) false
has2Fs(“fofo”) true
has2Fs(“foffo”) false

 

public boolean has2Fs3Gs(String str)

Description: This method returns true if str has exactly two occurrences of the letter ‘f’ in it and 3 occurences ‘g’.

Method Call return value/output
has2Fs3Gs(“foog”) false
has2Fs3Gs(“foggfog”) true
has2Fs3Gs(“foffoggg”) false

public int momOrDad(String str)

Description: This method returns the number of times that the String “mom” or the string “dad” occurs in the parameter str .

Method Call return value/output
momOrDad(“foog”) 0
momOrDad(“momf”) 1
momOrDad(“momdadmo”) 2
momOrDad(“momdadmom”) 3

 

public String threeTimes(String str)

Description: This method returns the String str concatenated with itself three times

Method Call return value/output
threeTimes(“foog”) “foogfoogfoog”
threeTimes(“abc”) “abcabcabc”
threeTimes(“zt”) “ztztzt”
threeTimes(“”) “”

 

public String nTimes(String str, int n)

Description: This method returns the String str concatenated with itself n times

Method Call return value/output
nTimes(“fg” , 2 ) “fgfg”
nTimes(“abc” , 0 ) “”
nTimes(“zt” , 3 ) “ztztzt”
nTimes(“uiz” , 4 ) “uizuizuizuiz”

 

 

public String countMiddleChar(String str)

Precondition: str.length() ≥ 3.

Description: This method returns the number of times the middle letter of str appears in str.

Method Call return value/output
countMiddleChar(“acbcb” ) 2
countMiddleChar(“acbcx” ) 1
countMiddleChar(“bbbbb” ) 5
countMiddleChar(“xytbtzy”) 1

 

 

public int indexOf(String haystack, String needle)

Description: Write your own indexOf() method. Obviously, you cannot make use of the String’s build in indexOf() method. This method returns the index of the first occurrence of needle in haystack . (Full credit if you can get this to work with Strings whose length is greater than 1).

Method Call return value/output
indexOf(“acxb”, “x” ) 2
indexOf(“zazt”, “z” ) 0
indexOf(“tayv”, “g” ) -1
indexOf(“hijklj”, “j” ) 2

If you want the extra credit, then it must also be able to complete the following example calls

Method Call return value/output
indexOf(“acxb”, “cx” ) 1
indexOf(“acxb”, “cxb” ) 1
indexOf(“acxb”, “cxbt” ) -1

 

public int countChars(String str, String chars)

Precondition:The length of chars is less than or equal to the length of str

Description: This method returns the number of times that charsoccurs in String str.

Method Call return value/output
countChars(“momdadmom” , “dad” ) 1
countChars(“foobofoo” , “foo”) 2
countChars(“foobofoofoo” , “foo”) 3
countChars(“foobofoofoo” , “xy” ) 0

Java String Loop Assingments 1

 

public void printTwos(String str)

Description: This method prints two letters from the String starting at with the first two letters and ending with the last two.

Method Call return value/output
printTwos(“abcdef”) “ab”
“bc”
“de”
“ef”

 

 

public void printReverse(String str)

Description: This method print every letter in reverse and on a new line.

Method Call return value/output
printReverse(“abcd”) “d”
“c”
“b”
“a”
printReverse(“thefoo”) “o”
“o”
“f”
“e”
“h”
“t”
public void printTwoReverse(String str)

Description: This method print every 2 letter in reverse and on a new line.

Method Call return value/output
printTwoReverse(“abcd”) “dc”
“cb”
“ba”
printTwoReverse(“thefoo”) “oo”
“of”
“fe”
“eh”
“ht”

 

public void printTwoReverseAgain(String str)

Description: This method print every 2 letter in reverse and on a new line and with no overlap of letters

Method Call return value/output
printTwoReverseAgain(“abcd”) “dc”
“ba”
printTwoReverseAgain(“thefoo”) “oo”
“fe”
“ht”