I am supposed to be creating an application to keep track of items for a local coffee shop, additionally provides a way to print out a listing of the items. I'm supposed to create a class named Item,
- A String instance variable to hold the item name
- A double instance variable to hold the price
- A co开发者_如何学JAVAnstructor that takes a String and double to initialize the instance variables
- A get and set method for each instance variable
Then I'm supposed to create a CoffeeDriver with these methods:
sortName
– this method sorts the array of items by item name and then displays the name and price of all items on the screensortPrice
– this method sorts the array of items by item price and then displays the name and price of all items on the screenmain
- It creates an array of Item objects using the data above to set each Item's information. After initializing the array, prompt the user for how they want to see the list – sorted by name or price. Then call the appropriate method.
This is the code I have so far for the coffee driver. This java thing is really hard for me :(
import javax.swing.*;
import java.text.DecimalFormat;
import java.util.*;
public class CoffeeDriver
{
public static void main(String[] args)
{
Item[] items = new Item[]
{
new Item("Donut", .75),
new Item("Coffee", 1.00),
new Item("Bagel", 1.25),
new Item("Milk", 1.50),
new Item("Water", 2.00)
};
Object[] possibleValues = { "Price", "Name" };
Object selectedValue = JOptionPane.showInputDialog(null,
"How would you like items sorted", "SORTING",
JOptionPane.INFORMATION_MESSAGE, null,
possibleValues, possibleValues[0]);
if(selectedValue == "Price")
{
System.out.println("sorting by price" + items);
}
}
public static void sortPrice(String[] name, double[] price)
{
DecimalFormat money = new DecimalFormat("$0.00");
arrays.sort(price);
JOptionPane.showMessageDialog(null, name[0]+ " " + money.format(price[0]) + "\n" +
name[1] + " " + money.format(price[1]) + "\n" +
name[2] + " " + money.format(price[2]) + "\n" +
name[3] + " " + money.format(price[3]) + "\n" +
name[4] + " " + money.format(price[4]));
}
}
}
if(selectedValue == "Price")
Don't use "==" to compare objects. Use the equals() method.
精彩评论