Question

In: Computer Science

Assignment 1: JAVA Classes, Objects, and Constructors The goal of this assignment is to get you...

Assignment 1: JAVA Classes, Objects, and Constructors

The goal of this assignment is to get you familiar with some of the most used JAVA syntax, as well as constructors objects, objects calling other objects, class and instance attributes and methods. You will create a small program consisting of Musician and Song classes, then you will have Musicians perform the Songs.

Included is a file “Assignment1Tester.java”. Once you have done the assignment and followed all instructions, you should be able to compile and run “Assignment1Tester.java”. If “Assignment1Tester.java” compiles and runs, this does not mean your code is correct. But it will make sure that your public facing interface and member variables have the correct specification.

Make certain all member variables and methods are exactly as requested. We may use automated marking, and if we do and you spell a member variable differently, you will not get the mark. That is why we highly encourage you to compile and run “Assignment1Tester.java”. It will check some of these things for you.

Every question is worth 5 marks.

1. Open the file “Musician.java”. There is a “static final” variable defaultNumberOfKnownSongs that has been initialized to 3. In the Musician class, we will add 3 more instance variables. The first should be called name and should be of typeString. The second should be called knownSongs and it should be an array of type Song. The third should be an int callednumKnownSongs.

2. Write a constructor that takes two arguments, “String name” and “int numberOfSongs”. Have this constructor initializeknownSongs to an array of Song with length numberOfSongs, and initialize the name instance variable to the name String that was passed in through the constructor. You should make use of the this keyword. Write a second constructor for theMusician class with a single argument “String name” that initializes knownSongs to an array of Song with lengthdefaultNumberOfKnownSongs. In both constructors initialize numKnownSongs to zero.

3. Write a public String toString(). If the name = “Slash” and he knows 2 songs, it should return a String “My name is Slash and I know 2 songs.”

4. Open the class “Song.java”. Write three constructors. Write a no-argument constructor that assigns the name “unknown” to the song name and “pop” to genre. Write a constructor that takes a String argument and assigns it to name, and assigns “pop” to genre. Write a constructor that takes two String arguments, the first of which is assigned to name and the second is assigned to genre. Make sure that “name” comes first in the constructor method signature.

5. Write a static method “randomSong()” that returns a Song object with a random name from the songNames array and a random genre from the songGenre array.

6. Write a method “public String toString()” that returns a String object describing the Song. That is, if name = “Paradise City” and genre = “hard rock”, then “public String toString()” should return the String “the hard rock song ‘Paradise City’.”

7. Write a method “equals(Song song)” in the Song class that compares the current Song object to the song variable. It returns true if the two songs have the same name and same genre, and false otherwise.

8. In the Musician class, write a method “public boolean learnSong(Song song)”. It should assign the song argument to the first open position in the knownSongs array. If the array is full it should not change the array and return false. If the array is not full, add the song and return true.

9. In the Musician class, write a method “public boolean playSong(Song song)”. If the song argument is equal to a song in the knownSongs array, then the method should output the Musicians name followed by “performs” followed by the song. For instance, if the Musician is named “Slash” and the song was ‘Paradise City’, it would print “Slash performs the hard rock song ‘Paradise City’.” to the screen and return true. Hint: you can make use of the toString() method of the Song class. If the Song argument is not equal to any Song in the knownSongs array, then this method should print “Slash does not know the hard rock song ‘Paradise City’.” and return false.

10. In the Musician class, write a method “public void playAllKnownSongs()”. This method should play every song in the knownSong array with each song formatted as in Question 9.

Solutions

Expert Solution

/***************************Musician.java*******************************/


public class Musician {

   /*
   * private data field
   */
   private static final int defaultNumberOfKnownSongs = 3;
   private String name;
   private Song[] knownSong;
   private int callednumKnownSongs;

   /**
   *
   * @param name
   * @param numberOfSongs
   */
   public Musician(String name, int numberOfSongs) {
       this.name = name;
       this.callednumKnownSongs = 0;
       this.knownSong = new Song[numberOfSongs];
   }

   /**
   *
   * @param name
   */
   public Musician(String name) {
       this.name = name;
       this.knownSong = new Song[defaultNumberOfKnownSongs];
       this.callednumKnownSongs = 0;
   }


   public static int getDefaultnumberofknownsongs() {
       return defaultNumberOfKnownSongs;
   }

   public String getName() {
       return name;
   }

   public Song[] getKnownSong() {
       return knownSong;
   }

   public int getCallednumKnownSongs() {
       return callednumKnownSongs;
   }

   @Override
   public String toString() {
       return "My name is " + name + " and i know " + callednumKnownSongs + "songs.";
   }

   public boolean learnSong(Song song) {

       if (knownSong.length - 1 == defaultNumberOfKnownSongs) {

           return false;
       } else {

           for (int i = knownSong.length - 1; i > 0; i--) {

               knownSong[i] = knownSong[i - 1];
           }

           knownSong[0] = song;
           return true;
       }
   }

   public boolean playSong(Song song) {

       int flag = 0;
       for (Song song1 : knownSong) {

           if (song1.equals(song)) {

               System.out.println(name + " performs " + song.toString());
               flag = 1;
           }
       }
       if (flag == 1) {

           return true;
       } else {

           return false;
       }
   }

   public void playAllKnownSongs() {

       for (Song song : knownSong) {

           System.out.println(name + " performs " + song.toString());
       }
   }
}
/********************************Song.java**************************/

import java.util.Random;

public class Song {

   private String songName;
   private String genre;

   public Song() {

       this.songName = "unknown";
       this.genre = "pop";
   }

   public Song(String name) {
       this.songName = name;
       this.genre = "pop";
   }

   public Song(String songName, String genre) {
       super();
       this.songName = songName;
       this.genre = genre;
   }

   public static Song randomSong(Song[] songs) {

       Random random = new Random();

       Song song = null;
       int randomIndex = random.nextInt(songs.length);

       for (int i = 0; i < songs.length; i++) {

           song = songs[randomIndex];
       }
       return song;
   }

   @Override
   public String toString() {
       return "The " + genre + " song " + "'" + songName + "'";
   }

   @Override
   public boolean equals(Object arg0) {
       Song other = (Song) arg0;
       if (this.songName.equalsIgnoreCase(other.songName) && this.genre.equalsIgnoreCase(other.genre)) {

           return true;
       } else {

           return false;
       }
   }

}

Please let me know if you have any doubt or modify the answer, Thanks :)


Related Solutions

How do objects enhance Java? How do objects relate to classes and methods?
How do objects enhance Java? How do objects relate to classes and methods?
Part 1 – Classes and objects Create a new Java project called usernamePart1 in NetBeans. In...
Part 1 – Classes and objects Create a new Java project called usernamePart1 in NetBeans. In my case the project would be called rghanbarPart1. Select the option to create a main method. Create a new class called Vehicle. In the Vehicle class write the code for: • Instance variables that store the vehicle’s make, model, colour, and fuel type • A default constructor, and a second constructor that initialises all the instance variables • Accessor (getters) and mutator (setters) methods...
Write a Java Program using the concept of objects and classes. Make sure you have two...
Write a Java Program using the concept of objects and classes. Make sure you have two files Employee.java and EmployeeRunner.java. Use the template below for ease. (Please provide detailed explanation) Class Employee Class Variables: Name Work hour per week Hourly payment Class Methods: - Get/Sets - generateAnnualSalary(int:Duration of employment)               annual salary = Hourly payment * Work hours per week * 50 If the employee is working for more than 5 years, 10% added bonus             -void displayAnnualSalary ( )...
Homework 3 – Programming with C++ What This Assignment Is About: • Classes and Objects •...
Homework 3 – Programming with C++ What This Assignment Is About: • Classes and Objects • Methods • Arrays of Primitive Values • Arrays of Objects • Recursion • for and if Statements • Insertion Sort 2. Use the following Guidelines • Give identifiers semantic meaning and make them easy to read (examples numStudents, grossPay, etc). • User upper case for constants. Use title case (first letter is upper case) for classes. Use lower case with uppercase word separators for...
The goal of Java program(s) implemented as part of this assignment is: 1. To use for,...
The goal of Java program(s) implemented as part of this assignment is: 1. To use for, while, do-while loops to solve the given problem(s) 2. Write custom method(s) Note: Be sure to document your code thoroughly. In other words, you must comment each pertinent line of code to briefly state what it is intending to do. Requirement-1 In the Requirement-1 you will create a program named ‘ComputeCompoundInterest, that will compute compound interest using the formula as follows: amount = principal...
*JAVA* For this assignment you have been given two classes, a Main.java and a Coin.java. The...
*JAVA* For this assignment you have been given two classes, a Main.java and a Coin.java. The coin class represents a coin. Any object made from it will have a 1) name, 2) weight and 3) value. As of now, the instance variables in Coin.java are all public, and the main function is calling these variables directly for the one coin made in it. Your goal is to enforce information hiding principles in this project. Take Coin.java, make all instance variables...
This is Python programming Focus 1. Classes and Objects 2. Creating objects 3. Manipulating objects This...
This is Python programming Focus 1. Classes and Objects 2. Creating objects 3. Manipulating objects This lab maps to learning the following objectives: Write a working program that creates a Class, Instances of Objects from that Class, and Functions that use Objects as parameters. For this portion of the lab, you will create a new program for your Professor. Create a class named Student that holds the following data about a student: 1. Name 2. Student ID number 3. GPA...
Using JAVA: This assignment is about aggregation and class collaboration. You will create several Classes that...
Using JAVA: This assignment is about aggregation and class collaboration. You will create several Classes that will be part of an overall class named InstrumentDisplay. The classes are FuelGage, Odometer, MilesSinceLastGas, and CruisingRange. The FuelGage should assume a 15 gallon tank of gasoline and an average consumption of 1 gallon every 28 miles. It should increment in 1 gallon steps when you "add gas to the tank". It should decrement by 1 every 28 miles. It should display its current...
The goal of Java program implemented as part of this assignment is to build an Inventory...
The goal of Java program implemented as part of this assignment is to build an Inventory Management System, from here on referred to as IMS, for a bookstore. You will need to do the following tasks: Requirement-1 – Create 3 different Arrays (15 pts) (a) Create an array named items that will hold the following item names (strings) - Pen - Pencil - Eraser - Marker - Notepad (b) Create a second array named quantity, that will hold corresponding quantities...
Question: Can I get the code in Java for this assignment to compare? Please and thank you....
Question: Can I get the code in Java for this assignment to compare? Please and thank you. Can I get the code in Java for this assignment to compare? Please and thank you. Description Write a Java program to read data from a text file (file name given on command line), process the text file by performing the following: Print the total number of words in the file. Print the total number of unique words (case sensitive) in the file. Print...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT