How would i write a program that says's..Welcome to Wings Coffee Shop. We have a great list items on our menu.Would you like to see items sorted by name or price? (n/p):n Item Name Price Bagel $1.25 Water $2.00 Coffee $1.00 Donut $0.75 Milk $1.50
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