Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Christina Zimmer
- import java.util.Scanner;
- import java.util.ArrayList;
- import java.util.Collections;
- class Taco implements Comparable {
- String name;
- double price;
- public Taco(String name, double price) {
- this.name = name;
- this.price = price;
- }
- public String toString() {
- String formattedPrice = String.format("$%.2f", this.price);
- return this.name + " - " + formattedPrice;
- }
- @Override
- public int compareTo(Object otherTaco) {
- double otherPrice=((Taco)otherTaco).price;
- /* For Ascending order of prices*/
- if(this.price < otherPrice) {
- return -1;
- } else {
- return 0;
- }
- }
- }
- public class HW4{
- public static void main(String []args){
- ArrayList<Taco> tacoList = new ArrayList<Taco>();
- int tacosNeeded = 10; //needed is variadic for convenience
- //2 scanners instead of 1 so there's no carriage consumption manipulations
- Scanner sNames = new Scanner(System.in); //scans strings only
- Scanner sPrices = new Scanner(System.in); //scans only doubles
- System.out.println("Welcome to the taco price sorter! Enter 10 taco names and prices and I’ll sort it!");
- //repeat 10 times to populate parallel arrays
- for(int i = 0; i < tacosNeeded; i++) {
- System.out.print("\nEnter name of taco " + (i+1) + ": ");
- String tacoName = sNames.nextLine();
- System.out.print("Enter price of taco " + (i+1) + ": ");
- double tacoPrice = sPrices.nextDouble();
- while(tacoPrice < 0) {
- //cheeky error message!
- System.out.print("\nError! Taco's cant be freeeee!\n(Enter a positive dollar amount this time): ");
- tacoPrice = sPrices.nextDouble();
- }
- tacoList.add(new Taco(tacoName, tacoPrice));
- }
- //sort backed by mergesort, overridden in compareTo in Taco
- Collections.sort(tacoList);
- System.out.println();
- //iterate through and output all the Tacos, ordered by price
- for(Taco t : tacoList) {
- System.out.println(t.toString());
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement