Chapter 5 Extra-Strength Methods

Chapter 5 Extra-Strength Methods

P5E

P5E.

  1. Create a class called “MySong”. Copy/Paste the following code in this class

import javax.swing.JOptionPane;
public class MySong
{
// Step 1: create instance variables
private String title;
private int rating;
// Step 2: Initialize variables in a constructor
public MySong()
{
title = new String( " " );
rating = 0;
} // end zero argument constructor Song
public MySong( String title, int rating )
{
this.title = title;
this.rating = rating;
} // end argument constuctor Song
public int getRating()
{
return this.rating = rating;
// prints individual variable
} // end method getRating
public void setRating( int rating )
{
String pass = JOptionPane.showInputDialog( "What is the password?" );
if( pass.equals( "pass" ) )
{
String setRate = JOptionPane.showInputDialog( "What rating do you want to give this?");
int newRating = Integer.parseInt( setRate );
this.rating = newRating;
} // end if
else
{
System.out.println( "\nWrong password\n" );
} // end else
} // end method setRating
public String toString()
{
String songInfo = new String();
songInfo = "Title is: " + title + " " +
"Rating: " + rating + " ";
return songInfo;
} // end method toString
} // end class MySong
  1. Create a class called “Jukebox”. A “Jukebox” will consist of a 2D array of MySong objects called songList. Write a program to perform the following tasks:

a.Write a zero-argument constructor to fill the jukebox with the following MySong objects and ratings or fill with your own songs. Copy and paste the following code to quickly fill up your jukebox free of charge…

songList[0][0] = new MySong( "Jet Airliner", 5 );

songList[0][1] = new MySong( "Slide", 4 );

songList[0][2] = new MySong( "Tom Sawyer", 3 );

songList[0][3] = new MySong( "Purple Rain", 2 );

songList[1][0] = new MySong( "Sing a Song", 1 );

songList[1][1] = new MySong( "Baba O'Riley", 5 );

songList[1][2] = new MySong( "Jumper", 4 );

songList[1][3] = new MySong( "Car Wash", 3 );

songList[2][0] = new MySong( "Kung Fu Fighting", 2 );

songList[2][1] = new MySong( "Right as Rain", 4 );

songList[2][2] = new MySong( "Beat It", 5 );

songList[2][3] = new MySong( "Bust a Move", 4 );

b.Write a toString() method that will traverse the 2D array songList and print all songs in the “Jukebox” using nested for-each loops. Design your toString() method to print out the songs in the “Jukebox” in a user-friendly format.

c.Write a method randomSong() that randomly picks a song to play. This can be done by using Math.random() to pick random numbers for a row and a column in the “Jukebox” and prints the name of the song at that location. Make sure that your code picks row/column combinations that are within the bounds of the 2D array.

d.Finally, write a method playSongofRating( int rating ) that takes an integer argument and prints only those songs in the “Jukebox” whose rating is equal to the parameter rating.