*question after 3 codes public class Instrument { private String name; private d
ID: 3833289 • Letter: #
Question
*question after 3 codes
public class Instrument {
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 getPictureUrl() {
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: " + 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;
}
}
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;
}
}
public class MusicStore {
/**
* @param args
*/
public static void main(String[] args) {
Instrument[] instruments = new Instrument[6];
fillInventory(instruments);
System.out.println("Below are the details of Inventory:");
for (int i = 0; i < instruments.length; i++) {
System.out.println("Name:"+instruments[i].getName());
System.out.println("Cost:"+instruments[i].getCost());
if(instruments[i] instanceof Percussion) {
System.out.println("Drum Type:"+((Percussion) instruments[i]).getDrumType());
System.out.println("Is Pitched:"+((Percussion) instruments[i]).isPitched());
}
}
}
public static void fillInventory(Instrument[] inst) {
Picture whistle= new Picture("Whistle.PNG");
Picture harp = new Picture("Harp.PNG");
Picture bell = new Picture("Bell.PNG");
Picture drum = new Picture("drum.jpg");
Picture gong = new Picture("Gong.PNG");
Picture cymbal = new Picture ("cymbals.jpg");
Sound whistle1 = new Sound ("Whistle.wav");
Sound harp1 = new Sound ("Harp.wav");
Sound bell1 = new Sound ("Bell.wav");
Sound drum1 = new Sound ("Drums.wav");
Sound gong1 = new Sound ("Gong.wav");
Sound cymbal1 = new Sound ("Cymbals.wav");
Instrument in1 = new Instrument("whistle", 75, whistle, whistle1);
inst[0] = in1;
Instrument in2 = new Instrument("harp",500.99, harp,harp1);
inst[1] = in2;
Percussion p1 = new Percussion("gong", 200, gong,gong1, "Basic", false);
inst[2] = p1;
Percussion p2 = new Percussion("cymbals", 232, cymbal, cymbal1, "Basic", true);
inst[3] = p2;
Instrument in3 = new Instrument();
String name = JOptionPane.showInputDialog("Enter name of the instrument : ");//Taking input using input box.
String cos = JOptionPane.showInputDialog("Enter cost of the instrument : ");
int cost = Integer.parseInt(cos);
in3.setCost(cost);
in3.setName(name);
in3.setPicture(whistle);
in3.setSound(whistle1);
inst[4] = in3;
Percussion p = new Percussion();
String name1 = JOptionPane.showInputDialog("Enter name of the percussion instrument : ");
String cos1 = JOptionPane.showInputDialog("Enter cost of the percussion instrument : ");
int cost1 = Integer.parseInt(cos1);
p.setCost(cost1);
p.setName(name1);
p.setDrumType("Drift");
p.setPitched(true);
p.setPicture(gong);
p.setSound(gong1);
inst[5] = p;
}
}
Add to music class with the following methods:
Call a method named updateObj2Cost
Display the cost of the second object
Set the cost of the second object in your array to 0
Display the cost of the second object again
Call a method named modifyObj3Image
Explore the picture for the third object in your array
Negate the picture for the third object in your array and explore it again
Call a method named modifyObj1Name
Display the name of the first object
Use a predefined method to modify/store the name of the first object to upper case
Display the name of the first object again
Call a method named copyDisplaySubclassObj
Create a new Percussion object and store one of your array objects in it. Display the subclass information only (no base class information) for that object. (hint: typecast)
Explanation / Answer
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;
/**
* @author Robin A.
*
*/
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);
}
}
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;
}
}
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;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.