In: Computer Science
Example input:
orange 0.80
pomegranate 2.50
plum 1.20
peach 1.00
persimmon 1.75
lime 0.60
END_PRICES
persimmon 2
orange 3
peach 1
plum 10
pomegranate 5
END_INVOICE
peach 11
plum 5
orange 1
lime 9
END_INVOICE
QUIT
For each invoice, the program should print a single line of the form Total: X.YY where X.YY is the total cost of the invoice, which is the sum of the costs of all of the line items in the invoice. The cost should be printed with exactly two digits after the decimal point.
Example output (corresponding to the input shown above):
Total: 31.40
Total: 23.20
Invoice.java
import java.util.*; public class Invoice { static final String endPrices = "END_PRICES"; static final String endInvoice = "END_INVOICE"; static final String quit = "QUIT"; public static void main(String... args) { Scanner sc = new Scanner(System.in); //HashMap to store fruit name as key and price as value Map<String, Float> fruits = new HashMap<>(); //Loop until input is not "END_PRICES" while (true){ String input = sc.next(); //Come out of loop if input is "END_PRICES" if(input.equals(endPrices)) break; float price = Float.parseFloat(sc.next()); //add fruit to hash map fruits.put(input, price); } //ArrayList to store total cost of each invoice List<Float> totalList = new ArrayList<>(); Float total = 0f; //loop until input becomes "QUIT" while (true){ String input = sc.next(); //Break out of the loop if input is "QUIT" if(input.equals(quit)){ break; } //Add total price of the invoice to array list and set total to "0f" to store total of next invoice if(input.equals(endInvoice)){ totalList.add(total); total = 0f; continue; } int quantity = sc.nextInt(); total += (fruits.get(input)*quantity); } //Iterate through all objects in the total Array List and print them Iterator itr = totalList.iterator(); while (itr.hasNext()){ System.out.printf("Total: %.2f \n", itr.next()); } } }
Sample Output: