Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

*Question after 3 programs import java.awt.Color; import java.awt.Font; import j

ID: 3834901 • Letter: #

Question

*Question after 3 programs

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.text.NumberFormat;

import javax.swing.JOptionPane;

/**
*
*/

/**
* @author
*
*/
public class Instrument {
   public NumberFormat nf = NumberFormat.getCurrencyInstance();
   private String name;

   private double cost;

   private Picture picture;

   private Sound sound;

   /**
   * no argument constructor
   */
   public Instrument() {

   }

   /**
   *
   * @param name
   *
   * @param cost
   *
   * @param picture
   *
   * @param sound
   *
   */

   public Instrument(String name, double cost, Picture picture, Sound sound) {

       this.name = name;

       this.cost = cost;

       this.picture = picture;

       this.sound = sound;

   }

   /**
   *
   * @return name
   *
   */

   public String getName() {

       return name;

   }

   /**
   *
   * @return cost
   *
   */

   public double getCost() {

       return cost;

   }

   /**
   *
   * @return picture
   *
   */

   public Picture getPicture() {

       return picture;

   }

   /**
   *
   * @return sound
   *
   */

   public Sound getSound() {

       return sound;

   }

   /**
   *
   * @param name
   *
   */

   public void setName(String name) {

       this.name = name;

   }

   /**
   *
   * @param cost
   *
   */

   public void setCost(double cost) {

       this.cost = cost;

       if (cost < 0)

           cost = 299.99;
       JOptionPane.showMessageDialog(null, "Cost is less than zero, default cost set to $299.99");
   }

   /**
   *
   * @param picture
   *
   */

   public void setPicture(Picture picture) {

       this.picture = picture;

   }

   /**
   *
   * @param sound
   *
   */

   public void setSound(Sound sound) {

       this.sound = sound;

   }

   @Override

   public String toString() {

       return "Name: " + name + ", Cost: " + nf.format(cost) + ", Picture Url: " + picture + ", Sound: " + sound;

   }

   public Picture labelImage(Color c, int fontSize)
   {
       Picture temp = picture;
       Graphics g = temp.getGraphics();
       g.setColor(c);
       g.setFont(new Font("Arial",Font.BOLD,fontSize));
       g.drawString(name, 25, 75);
       return temp;
      
   }

}

/**
*
*/

/**
* @author
*
*/
public class Percussion extends Instrument {
   private String drumType;
   private boolean pitched;
   /**
   *no argument constructor
   */
   public Percussion() {
   }

   /**
   * @param name
   *
   * @param cost
   *
   * @param pictureUrl
   *
   * @param sound
   *
   * @param drumType
   *
   * @param pitched
   *
   */

   public Percussion(String name, double cost, Picture picture,

           Sound sound, String drumType, boolean pitched) {

       super(name, cost, picture, sound);

       this.drumType = drumType;

       this.pitched = pitched;
   }

   /**
   *
   * @return drumType
   *
   */

   public String getDrumType() {

       return drumType;

   }

   /**
   *
   * @return pitched
   *
   */

   public boolean isPitched() {

       return pitched;

   }

   /**
   *
   * @param drumType
   *
   */

   public void setDrumType(String drumType) {

       this.drumType = drumType;

   }

   /**
   *
   * @param pitched
   *
   */

   public void setPitched(boolean pitched) {

       this.pitched = pitched;

   }

   @Override

   public String toString() {

       return super.toString() + ", Drum Type" + drumType + ", Is pitched: " + pitched;

   }
}

import java.text.NumberFormat;

import javax.swing.JOptionPane;

/**
*
*/

/**
* @author
*
*/
public class MusicStore {

   /**
   * @param args
   */
   public static void main(String[] args) {
       Instrument [] inventory = new Instrument [6];
   TestMusicStore store = new TestMusicStore();
   store.fillInventory(inventory);
   store.displayMenu(inventory);
       }
   public NumberFormat nf = NumberFormat.getCurrencyInstance();
  
   /**
   * @param inventory
   */
   public void fillInventory (Instrument [] inventory) {
       inventory[0] = new Instrument("Whistle", 62.55, new Picture ("Whistle.PNG"), new Sound ("Whistle.wav"));
   inventory[1] = new Instrument("Harp", 599.99, new Picture ("Harp.PNG"), new Sound ("Harp.wav"));
   inventory[2] = new Percussion("Bongos", 49.99, new Picture ("Bongos.PNG"), new Sound ("Bongos.wav"), "macho", false);
   inventory[3] = new Percussion("Drums", 200.99, new Picture ("drum.jpg"), new Sound ("Drums.wav"), "bass", true);
     
   inventory[4] = new Instrument();
   String tName = JOptionPane.showInputDialog("Please Enter name of an instrument");
   String tcost = JOptionPane.showInputDialog("How much does " + tName + " cost?");
   inventory[4].setName(tName);
   double tCost = 0.0;
   inventory[4].setCost(tCost);
   inventory[4].setPicture(new Picture ("Bell.PNG"));
   inventory[4].setSound(new Sound ("Bell.wav"));
  
   inventory[5] = new Percussion();
   tName = JOptionPane.showInputDialog("Enter Name of a percussion instrument");
   inventory[5].setName(tName);
   tCost = Double.parseDouble(JOptionPane.showInputDialog("How much does " + tName + " cost?"));
   inventory[5].setCost(tCost);
   inventory[5].setPicture(new Picture ("cymbals.jpg"));
   inventory[5].setSound(new Sound ("Cymbals.wav"));
   ((Percussion)inventory[5]).isPitched();
   ((Percussion)inventory[5]).setDrumType("crash");
   }
  
   public void displayMenu(Instrument [] inventory) {
      
       int userSelection = Integer.parseInt(JOptionPane.showInputDialog("Please choose from the following: 1) Select an instrument 2) Display Inventory 3) Listen to Inventory"
+ " 4) Display Total Inventory Values 5) Display Labeled Images 6) Execute final four methods 7 Exit"));
      
   }
}
*Add to MusicStore to do the following:

Call a method named displayMenu with the following choices

1.Select an Instrument

Use a linear search to look for that instrument by name

If the instrument is found display another menu with these choices

Image – displays the object’s image

Sound – plays the object’s sound

Compare Price – finds the first occurrence of this object’s price on Amazon.com using search sequence “suggested retail price”. If found, compare to stored price and determine best deal, else display message.

(http://www.amazon.com/s/ref=nb_sb_noss_1?url=search-alias%3Daps&field-keywords= )    use eBay instead

Exit

If the instrument is not found display a message saying so

Explanation / Answer

Instrument.java


import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.text.NumberFormat;
import javax.swing.JOptionPane;;


public class Instrument {
  
   public NumberFormat nf = NumberFormat.getCurrencyInstance();
   private String name;
   private double cost;
   private Picture pic;
   private Sound sound;
  
   /**
   * Default Constructor
   */
   public Instrument () {
       name = "Unknown";
       cost = 299.99;
   }
  
   /**
   * Overloaded constructor
   * @param name - name of instrument
   * @param cost - cost of instrument
   * @param pic - pic of instrument
   * @param sound - sound file of instrument
   */
   public Instrument (String name, double cost, Picture pic, Sound sound) {
       this.name = name;
       this.pic = pic;
       this.sound = sound;
      
       if (cost > 0) {
           this.cost = cost;
       }
       else {
           JOptionPane.showMessageDialog(null, "Invalid price set for instrument. Setting to default value of 299.99");
           this.cost = 299.99;
       }
   }

   /**
   * @return the name
   */
   public String getName() {
       return name;
   }

   /**
   * @param name the name to set
   */
   public void setName(String name) {
       this.name = name;
   }

   /**
   * @return the cost
   */
   public double getCost() {
       return cost;
   }

   /**
   * Sets cost to user value, sets a default value if user value is 0 or less
   * @param cost the cost to set
   */
   public void setCost(double cost) {
       if (cost > 0) {
           this.cost = cost;
       }
       else {
           JOptionPane.showMessageDialog(null, "Invalid price set for instrument. Setting to default value of " + nf.format(299.99));
           this.cost = 299.99;
       }
   }

   /**
   * @return the pic
   */
   public Picture getPic() {
       return pic;
   }

   /**
   * @param pic the pic to set
   */
   public void setPic(Picture pic) {
       this.pic = pic;
   }

   /**
   * @return the sound
   */
   public Sound getSound() {
       return sound;
   }

   /**
   * @param sound the sound to set
   */
   public void setSound(Sound sound) {
       this.sound = sound;
   }
  
   /**
   * Prints the name of the instrument onto the picture with the passed color and font size from user
   * @param c - Color of font
   * @param fontSize - Size of Font
   * @return - new picture with name label on top left
   */
   public Picture labelImage (Color c, int fontSize) {
       Picture temp = pic;
       Graphics g = temp.getGraphics();
       g.setColor(c);
       g.setFont(new Font("Consolas", Font.BOLD, fontSize));
       g.drawString(name, 25, 75);
       return temp;
   }

   /* (non-Javadoc)
   * @see java.lang.Object#toString()
   */
   @Override
   public String toString() {
       return "Instrument: " + name + ", costs " + nf.format(cost) + ", pic info: " + pic + ", sound info: " + sound;
   }
  
}


MusicStore.java

import java.awt.Color;
import java.io.*;
import java.net.URL;
import java.text.NumberFormat;
import java.util.Random;
import javax.swing.JOptionPane;


public class MusicStore {
   public NumberFormat nf = NumberFormat.getCurrencyInstance();

   /**
   * Fills a passed Instrument array with the values of different Instrument and Percussion objects; some filled for you, some given
   * a name by the user (original idea was to have the name be used to call the pic and sound file too, and while it worked just fine, it was
   * a bit of a pain through testing, where I didn't want to type the full name of a valid item every time I needed to test)
   * @param inventory - Passed Instrument array from calling method
   */
   public void fillInventory (Instrument [] inventory) {
      
       boolean doubleCheck = false;
       inventory[0] = new Instrument("Whistle", 39.99, new Picture ("whistle.png"), new Sound ("whistle.wav"));
       inventory[1] = new Instrument("Harp", 599.99, new Picture ("harp.png"), new Sound ("harp.wav"));
       inventory[2] = new Percussion("Bongos", 49.99, new Picture ("bongos.png"), new Sound ("bongos.wav"), "macho", false);  
       inventory[3] = new Percussion("Drums", 200.99, new Picture ("drums.png"), new Sound ("drums.wav"), "bass", true);
      
       inventory[4] = new Instrument();
       String tempName = JOptionPane.showInputDialog("Say name");  
       inventory[4].setName(tempName);
       double tempCost = 0.0;
      
       while (!doubleCheck) {
           try {
               tempCost = Double.parseDouble(JOptionPane.showInputDialog("How much does " + tempName + " cost?"));
               doubleCheck = true;
           } catch (NumberFormatException e) {
               JOptionPane.showMessageDialog(null, "Please enter a valid number!");
           }
       }
      
       inventory[4].setCost(tempCost);
       inventory[4].setPic(new Picture ("bell.png"));
       inventory[4].setSound(new Sound ("bell.wav"));
      
       inventory[5] = new Percussion();
       tempName = JOptionPane.showInputDialog("Say name");  
       inventory[5].setName(tempName);
       doubleCheck = false;
      
       while (!doubleCheck) {
           try {
               tempCost = Double.parseDouble(JOptionPane.showInputDialog("How much does " + tempName + " cost?"));
               doubleCheck = true;
           } catch (NumberFormatException e) {
               JOptionPane.showMessageDialog(null, "Please enter a valid number!");
           }
       }
      
       inventory[5].setCost(tempCost);
       inventory[5].setPic(new Picture ("cymbals.png"));
       inventory[5].setSound(new Sound ("cymbals.wav"));
       ((Percussion)inventory[5]).isPitched();
       ((Percussion)inventory[5]).setDrumType("crash");
   }
  
   /**
   * Method which sets up the GUI which is used to allow the user to dictate how the program works. A higher focus on method calls and separating some of this bloated
   * method into smaller separate methods would have been wise, but things worked well enough!
   * @param inventory - passed Instrument array
   */
   public void displayMenu(Instrument [] inventory) {
  
       int userSelection = 0;
       String userInstrument = "";
       boolean exit;
       boolean properSelection;
       int i = 0;
      
       while (true) {
           properSelection = false;
           exit = false;
          
           try {
               userSelection = Integer.parseInt(JOptionPane.showInputDialog("Please choose from the following: 1) Select an instrument 2) Display Inventory 3) Listen to Inventory"
                       + " 4) Display Total Inventory Values 5) Display Labeled Images 6) Exit"));
           } catch (NumberFormatException e) {
               JOptionPane.showMessageDialog(null, "Please only enter numbers!");
               // Previous command iterates again after exception catch if user value isn't reset; I found it annoying
               userSelection = 0;
           }
          
           switch (userSelection) {
           case 1:
               while (!properSelection) {
                   userInstrument = JOptionPane.showInputDialog("Which instrument would you like to select?");
                   for (i = 0; i < inventory.length; i++){
                       if (userInstrument.toLowerCase().compareTo(inventory[i].getName().toLowerCase()) == 0) {
                           properSelection = true;
                           break;
                       }
                   }
                   if (!properSelection) {
                       JOptionPane.showMessageDialog(null, "Item not found in inventory. Please try again");
                   }
               }
               properSelection = false;
               while(!exit) {
                   try {
                       userSelection = Integer.parseInt(JOptionPane.showInputDialog("What would you like to do? 1) Display image of " + userInstrument
                               + " 2) Play sound of " + userInstrument + " 3) Compare prices of " + userInstrument + " 4) Exit"));
                   } catch (NumberFormatException e) {
                       JOptionPane.showMessageDialog(null, "Please only enter numbers!");
                       // Same as above
                       userSelection = 0;
                   }
                  
                   switch (userSelection) {
                   case 1:
                       (inventory[i].getPic()).show();
                       break;
                   case 2:
                       (inventory[i].getSound()).play();
                       break;
                   case 3:
                       String fileName = "https://www.walmart.com/search/?query=" + inventory[i].getName().toLowerCase() + "&cat_id=4171_1015079";
                       String seq = "baseprice=";
                       String price = "";
                       String line = null;
                       double comparePrice = 0.0;
                       String bestPrice = "";
                      
                       try {
                           URL url = new URL (fileName);
                           InputStream inStr = url.openStream();
                           BufferedReader reader = new BufferedReader(new InputStreamReader(inStr));
                          
                           while ((line = reader.readLine()) != null && line.indexOf(seq) < 0) {}  
                          
                           if (line != null) {
                               int seqIndex = line.indexOf(seq) + 9;
                               int stopIndex = line.indexOf(" dohideitemcontrols");
                               price = line.substring(seqIndex + 1, stopIndex);
                           }
                           comparePrice = Double.parseDouble(price);
                       } catch (FileNotFoundException ex) {
                           JOptionPane.showMessageDialog(null,"Couldn't find file " + fileName);                          
                       } catch (Exception ex) {
                           JOptionPane.showMessageDialog(null,"Error during read or write");
                           ex.printStackTrace();
                       }
                      
                       if (comparePrice == 0) {
                           break;
                       }
                       if (comparePrice > inventory[i].getCost()) {
                           bestPrice = "We have";
                       }
                       else if (comparePrice < inventory[i].getCost()) {
                           bestPrice = "Competitor has";
                       }
                       JOptionPane.showMessageDialog(null, "Competitor sells " + inventory[i].getName() + " for " + nf.format(comparePrice) +"; we sell " + inventory[i].getName()
                               + " for " + nf.format(inventory[i].getCost())   + " " + bestPrice + " the best price");
                       break;
                   case 4:
                       exit = true;
                   }
               }
               break;
              
           case 2:
               String allValues = "";
               for (Instrument j: inventory) {
                   allValues += j + " ";
               }
               JOptionPane.showMessageDialog(null, allValues);
               break;  
              
           case 3:
               i = 0;
               while (i < inventory.length) {
                   inventory[i].getSound().blockingPlay();
                   i++;
               }
               break;
              
           case 4:
               double totalValue = 0;
               for (i = 0; i < inventory.length; i++) {
                   totalValue += inventory[i].getCost();
               }
               JOptionPane.showMessageDialog(null, "The total cost of all the items in our inventory is " + nf.format(totalValue));
               break;
              
           case 5:
               Picture label = new Picture ();
               int imgSize = 36;
               for (i = 0; i < inventory.length; i++) {
                   label = inventory[i].labelImage(randColor(), imgSize);
                   label.show();
                   try {
                       Thread.sleep(500);
                   } catch (InterruptedException ex) {
                       Thread.currentThread().interrupt();
                   }
                   // Makes it so the font size changes without having to input a different size each time, to meet the 3 different size requirement
                   imgSize = (imgSize < 72) ? imgSize + 12 : imgSize - 36;
               }
               break;
              
           case 6:
               updateObj2Cost(inventory);
               modifyObj3Image(inventory);
               modifyObj1Name(inventory);
               copyDisplaySubclassObj(inventory);
               return;
           }
       }
   }
  
   /**
   * Works alongside the 5th option to label and print each image in inventory as to print different colors without having to manually call the method a bunch of times
   * with different parameters, to meet the 3 color requirement (although the chance of only showing 2 of the 6 colors is still possible, even if the odds are low)
   * @return - returns randomly selected color to calling method
   */
   public Color randColor () {
       Color [] randColor = {Color.RED, Color.BLUE, Color.GREEN, Color.PINK, Color.ORANGE, Color.BLACK};
       Random rand = new Random ();
       int randNum = rand.nextInt(6);
       return randColor[randNum];
   }
  
   /**
   * Changes the cost variable of the second object in the array to an invalid (0 or less) number, to invoke the default price
   * @param inventory
   */
   public void updateObj2Cost (Instrument [] inventory) {
       JOptionPane.showMessageDialog(null, "The current cost of " + inventory[1].getName() + " is " + nf.format(inventory[1].getCost()));
       inventory[1].setCost(0.0);
       JOptionPane.showMessageDialog(null, "The updated cost of " + inventory[1].getName() + " is " + nf.format(inventory[1].getCost()));
   }

   /**
   * Shows the image currently stored in the third object, negates the picture, and shows it once more.
   * @param inventory - passed Instrument array
   */
   public void modifyObj3Image (Instrument [] inventory) {
       Picture pic = new Picture (inventory[2].getPic());
       JOptionPane.showMessageDialog(null, "Picture of " + inventory[2].getName());
       pic.show();
       negate(pic);
       JOptionPane.showMessageDialog(null, "Picture of " + inventory[2].getName() + " negated");
       pic.hide();
       pic.show();
      
       try {
           Thread.sleep(1000);
           pic.hide();
       }
       catch (InterruptedException ex){
           Thread.currentThread().interrupt();
       }
   }
  
   /**
   * Changes the name value of the first object to the same name, but all uppercase
   * @param inventory - passed instrument array
   */
   public void modifyObj1Name(Instrument [] inventory) {
       JOptionPane.showMessageDialog(null, "The current name of the first item is " + inventory[0].getName());
       inventory[0].setName(inventory[0].getName().toUpperCase());
       JOptionPane.showMessageDialog(null, "The name has been changed to " + inventory[0].getName());
   }
  
   /**
   * Takes a percussion object in the passed array (predetermined), makes a copy, and prints only the percussion-unique values in it
   * @param inventory - passed instrument array
   */
   public void copyDisplaySubclassObj (Instrument [] inventory) {
       Percussion obj = (Percussion)inventory[5];
       String isPitched = (obj.isPitched()) ? "is pitched" : "is not pitched";
       JOptionPane.showMessageDialog(null, "The type of drum is " + obj.getDrumType() + " and it " + isPitched);
   }

   /**
   * Takes the passed picture, negates the colors, and passes it back to calling method
   * @param pic - passed Picture object
   */
   public void negate(Picture pic) {
       Pixel[] pixelArray = pic.getPixels();
       Pixel pixel = null;
       int redValue, blueValue, greenValue = 0;

       for (int i = 0; i < pixelArray.length; i++) {
           pixel = pixelArray[i];
          
           redValue = pixel.getRed();
           greenValue = pixel.getGreen();
           blueValue = pixel.getBlue();
          
           pixel.setColor(new Color (255 - redValue, 255 - greenValue, 255 - blueValue));
       }
   }
  
   public static void main(String[] args) {
       Instrument [] inventory = new Instrument [6];
       MusicStore store = new MusicStore();
       store.fillInventory(inventory);
       store.displayMenu(inventory);
   }
}


Percussion.java


public class Percussion extends Instrument {
  
   private String drumType;
   private boolean pitched;
  
   /**
   * Default constructor
   */
   public Percussion () {
       super();
       drumType = "unknown";
       pitched = false;
   }
  
   /**
   * Overload constructor for the Instrument class
   * @param name - name of instrument
   * @param cost - how much it costs
   * @param pic - picture of instrument
   * @param sound - sound file of instrument
   * @param drumType - what type of drum it is
   * @param pitched - whether it's pitched or not
   */
   public Percussion (String name, double cost, Picture pic, Sound sound, String drumType, boolean pitched) {
       super(name, cost, pic, sound);
       this.drumType = drumType;
       this.pitched = pitched;
   }

   /**
   * @return the drumType
   */
   public String getDrumType() {
       return drumType;
   }

   /**
   * @param drumType the drumType to set
   */
   public void setDrumType(String drumType) {
       this.drumType = drumType;
   }

   /**
   * @return the pitched
   */
   public boolean isPitched() {
       return pitched;
   }

   /**
   * @param pitched the pitched to set
   */
   public void setPitched(boolean pitched) {
       this.pitched = pitched;
   }

   /* (non-Javadoc)
   * @see java.lang.Object#toString()
   */
   @Override
   public String toString() {
       return super.toString() + " type of drum: " + drumType + ", is pitched: " + pitched;
   }
  
}