So I have a question on what to do next. I am working on this program and the requirements are.
Wings Coffee Shop
A local coffee shop sells a variety of different items shown below to their customers. You are asked to write a Java application that can be used to keep track of these items. Additionally, this program provides a way to print out a listing of the items.
Item Name Price
Coffee $1.00
Water $2.00
Milk $1.50
Bagel $1.25
Donut $0.75
Your program will create a class, named Item. This class has the following:
- A String instance variable to hold the item name
- A double instance variable to hold the price
- A constructor that takes a String and double to ini
Once you have this class created, you write a second class named CoffeeDriver. This class has the following methods:
- sortName – this method sorts the array of items by item name and then displays the name and price of all items on the screen
- sortPrice – this method sorts the array of items by item price and then displays the name and price of all items on the screen
- main – It creates an array of Item objects using the data above to set each Item’s information.
- A get and set method for each instance variable
This is all I have so far. I am having a hard time thinking how to sort an array. So if I sort 2 different arrays how do I keep them in proper order. Like for instance coffee = $1 how do I sort it and keep those together.
import java.util.Scanner;
public class CoffeeDriver {
//main method
public static void main (String[] args){
String[] itemName = {"Coffee, Water, Milk, Donut, Bagel"};
double[] itemPrice = {1.00, 2.00, 1.50, 0.75, 1.25};
Scanner input = new Scanner(System.in);
String decision;
System.out.println ("Welcome to Wings Coffee Shop");
System.out.println ("We have a great list of tasty items on our menu.");
System.out.println ("Would you like to see these items sorted by");
System.out.println ("name or by price? (n/p): ");
decision = input.nextLine();
if (decision == "n"){
sortName(itemName);
}
else {
sortPrice(itemPrice);
}
}
//method to sort by item name and display
public static void sortName (String[] array){
for (int i = 0; i < array.length; i++){
System.out.println (array[i].toString());
}
}
//method to sort by item price and display
public static void sortPrice (double[] array){
for (int i = 0; i < array.length; i++){
System.out.println (array[i]);
}
}
}
public class Item {
private String name;
private double price;
Item(String itemName, double itemPrice){
itemName = name;
itemPrice= price;
}
public String getName(){
return name;
}
public void setName(String itemName){
itemName = name;
}
public double getPrice(){
return price;
}
public void setPrice(double itemPrice){
itemPrice = price;
}
}
Correction to the Item class definition.
You need to assign parameters to the fields (In OP you’ve assign field to parameter)
Use Comparator object parameter to implement sorting for individual field.