How do i create a program that 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 initialize the instance variables * A get and set method for each instance variable do i create a program
next Once i have this class created, i need to 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. 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.
import java.util.*; class Item { String name; double price; Item(String name,double price){ this.name=name; this.price=price; } public void setName(String name){ this.name = name; } public String getName() { return name; } public void setPrice(double price) { this.price = price; } public double getPrice(){ return price; } } class NameComparator implements Comparator{ public int compare(Object o1, Object o2){ String name1 = ((Item)o1).getName(); String name2 = ((Item)o2).getName(); return name1.compareTo(name2); } } class PriceComparator implements Comparator{ public int compare(Object o1, Object o2){ if (((Item)o1).getPrice() < ((Item)o2).getPrice()) return -1; if (((Item)o1).getPrice() > ((Item)o2).getPrice()) return 1; return 0; } } class CoffeeDriver { static ArrayList<Item> list=new ArrayList<Item>(); public static void sortName(){ Collections.sort(list,new NameComparator()); for(Item data: list){ System.out.println(data.getName()+"\t "+data.getPrice()); } } public static void sortPrice(){ Collections.sort(list,new PriceComparator()); for(Item data: list){ System.out.println(data.getName()+"\t "+data.getPrice()); } } public static void main(String[] args) { Scanner input=new Scanner(System.in); list.add(new Item("Bagel",1.25)); list.add(new Item("Water",2.00)); list.add(new Item("Coffee",1.00)); list.add(new Item("Donut",0.75)); list.add(new Item("Milk",1.50)); System.out.println("Sorted By Name"); System.out.println("Sorted By Price"); System.out.println("Exit"); boolean exit=false; do{ System.out.print("Enter your choice: "); int choice=input.nextInt(); switch(choice){ case 1: sortName(); break; case 2: sortPrice(); break; case 3: exit=true; break; default: System.out.println("Invalid"); } } while(!exit); } }
Ads