OnJava8-Examples/strings/ReceiptBuilder.java

49 lines
1.5 KiB
Java
Raw Normal View History

2015-12-15 11:47:04 -08:00
// strings/ReceiptBuilder.java
2016-12-30 17:23:13 -08:00
// (c)2017 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2015-06-15 17:47:35 -07:00
import java.util.*;
2015-12-15 11:47:04 -08:00
public class ReceiptBuilder {
2015-06-15 17:47:35 -07:00
private double total = 0;
2016-01-25 18:05:55 -08:00
private Formatter f =
new Formatter(new StringBuilder());
2015-12-15 11:47:04 -08:00
public ReceiptBuilder() {
f.format(
"%-15s %5s %10s%n", "Item", "Qty", "Price");
f.format(
"%-15s %5s %10s%n", "----", "---", "-----");
2015-06-15 17:47:35 -07:00
}
2015-12-15 11:47:04 -08:00
public void add(String name, int qty, double price) {
f.format("%-15.15s %5d %10.2f%n", name, qty, price);
2015-06-15 17:47:35 -07:00
total += price * qty;
}
2015-12-15 11:47:04 -08:00
public String build() {
f.format("%-15s %5s %10.2f%n", "Tax", "",
total * 0.06);
f.format("%-15s %5s %10s%n", "", "", "-----");
f.format("%-15s %5s %10.2f%n", "Total", "",
2015-06-15 17:47:35 -07:00
total * 1.06);
2015-12-15 11:47:04 -08:00
return f.toString();
2015-06-15 17:47:35 -07:00
}
public static void main(String[] args) {
ReceiptBuilder receiptBuilder =
new ReceiptBuilder();
2015-12-15 11:47:04 -08:00
receiptBuilder.add("Jack's Magic Beans", 4, 4.25);
receiptBuilder.add("Princess Peas", 3, 5.1);
receiptBuilder.add(
"Three Bears Porridge", 1, 14.29);
2015-12-15 11:47:04 -08:00
System.out.println(receiptBuilder.build());
2015-06-15 17:47:35 -07:00
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
Item Qty Price
---- --- -----
Jack's Magic Be 4 4.25
Princess Peas 3 5.10
Three Bears Por 1 14.29
Tax 2.80
-----
Total 49.39
2015-09-07 11:44:36 -06:00
*/