Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.List;
- public class OutputFormatted {
- private List<String> items = new ArrayList<String>();
- private List<Integer> quantities = new ArrayList<Integer>();
- private List<Double> prices = new ArrayList<Double>();
- private int longestItemName;
- private int longestQuantity;
- private int longestPrice;
- private int longestTotal;
- public static void main(String[] args) {
- OutputFormatted output = new OutputFormatted();
- output.newPurchase("Soap", 5, 1.95);
- output.newPurchase("Computer", 2, 1050.50);
- output.newPurchase("Chips", 10, 0.95);
- output.output();
- }
- public void newPurchase(String name, int quantity, double price) {
- items.add(name);
- quantities.add(quantity);
- prices.add(price);
- // whenever we add a new item, we compare the length of the string
- // it would produce with what is the current longest string.
- longestItemName = longest(longestItemName, name);
- longestQuantity = longest(longestQuantity, quantity);
- longestPrice = longestPrice(longestPrice, price);
- longestTotal = longestPrice(longestTotal, (quantity * price));
- }
- public void output() {
- // extra padding just to make it look a bit nicer.
- // caution: it gets added whenever you call output.
- int extraSpacePadding = 5;
- longestItemName += extraSpacePadding;
- longestQuantity += extraSpacePadding;
- longestPrice += extraSpacePadding;
- longestTotal += extraSpacePadding;
- for(int i = 0; i < items.size(); i++) {
- // using the %-NUMBERd formatting where
- // NUMBER represents how much space is padded in.
- System.out.printf("%-"+longestItemName+"s %-"+longestQuantity+"d %-"+longestPrice+".2f %-"+longestTotal+".2f\n", items.get(i), quantities.get(i), prices.get(i), quantities.get(i) * prices.get(i));
- }
- }
- private int longest(int i1, String s2) {
- String s1 = String.valueOf(i1);
- if(s1.length() > s2.length()) return s1.length();
- return s2.length();
- }
- private int longestPrice(double d1, double d2) {
- int i1 = (int)d1;
- int i2 = (int)d2;
- // make sure they're always at 2 decimal points.
- // basically converting it a int will get rid of
- // all the decimal points that doubles may have.
- // add 2 since we always format prices as 2 decimal
- // points. beware of rounding errors. i was too lazy
- // to check that.
- return longest(i1, i2) + 2;
- }
- private int longest(int i1, int i2) {
- String s2 = String.valueOf(i2);
- return longest(i1, s2);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement