Java Genesis

Hints for Chapter 5: Arrays

Problem 14: corner store

This is essentially an exercise in formatting output. We want to display all monetary values with two digits after the decimal point to denote the cents. Here is our complete class for the modified CornerStore class:

   import genesis.*;

   class CornerStore {
	
  	public static void main (String [] args) {
  	   int [] [] purchases = { {3, 4, 6, 2},
                                 {1, 3, 7, 3},
                                 {2, 3, 8, 0},
                                 {1, 4, 3, 1},
                                 {0, 0, 7, 0}
                               };
    	   int [] costPerItem = {230, 160, 90, 160};
  	   String [] costPerItemAsString =
                {"$2.30", "$1.60", "$0.90", "$1.60"};
    	   // set up item names for each product
    	   String [] itemNames = {"butter", "milk", "paper", "bread"};
    	   // for each customer
    	   for (int i = 0; i < purchases.length; i++) {
                 // calculate debt and produce itemised account
                 int debt = 0;
                 Transcript.println("CUSTOMER:   " + i);
                 // for each grocery item
                 for (int j = 0; j < purchases[i].length; j++) {
                         if (purchases[i][j] != 0) {
                           int itemCost = purchases[i][j] * costPerItem[j];
                           String itemCostAsString;
                           if (itemCost%100 < 10)
                             itemCostAsString = 
                                "$"+itemCost/100+".0"+itemCost%100;
                           else itemCostAsString = 
                                "$"+itemCost/100+"."+itemCost%100;
                           debt = debt + itemCost;
                           Transcript.println(
                                purchases[i][j]+" units of "+itemNames[j]+ 
                                  " at "+costPerItemAsString[j]+
                                  "\t"+itemCostAsString);
                         }                          
                 }
                 // produce final total debt line
                 String debtAsString;
                 if (debt%100 < 10)
                    debtAsString = "$"+debt/100+".0"+debt%100;
                 else debtAsString = "$"+debt/100+"."+debt%100;
                 Transcript.println("Total\t\t"+ debtAsString);
    	   }
 	}
   }