/* T01n08.java -- Time for a story! * * One day a traveller arrives in the kingdom and is greeted by the king. * The traveller arranges to teach the king a new game called "tic-tac-toe", * and the king is so delighted by the new game that he offers the traveller * any reward he wishes. The traveller merely asks the king for 1 cent * for the first square on the board, 2 cents for the second, 4 * cents for the third, etc. The king is amazed that the traveller asks * so little for this knowledge, but agrees to pay. This program * determines how much the king agreed to pay. * * This program demonstrates a while loop, as well as output formatting * with the printf() statement. * * Something else to note: The program doesn't just display the answer; * it shows the intermediate results, too. This is very useful information * to have when you are debugging your code. Without it, if you had an * off-by-one error in your loop, you could report a total of $10.23 * without being aware of the error. The extra printing can be easily * commented-out when you feel that the code is working correctly. Why * not just delete it? Because what usually happens is this: As soon as * your testing code is removed, you'll notice another bug! */ public class T01n08 { public static void main (String [] args) { final int NUM_SQUARES = 9; // squares on a tic-tac-toe board float currentSum, // total worth of the squares considered so far currentValue; // value of the square being considered int square; // identifier of the square being considered currentValue = 1; currentSum = 1; // sum is 1 *after* considering square 1 System.out.println("Square\t Cost\t Total"); System.out.printf("%6d\t%6.1f\t%6.1f\n",1,currentValue,currentSum); square = 2; // start the loop with square 2 while (square <= NUM_SQUARES) { currentValue = currentValue * 2; currentSum = currentSum + currentValue; System.out.printf("%6d\t%6.1f\t%6.1f\n",square,currentValue, currentSum); square = square + 1; } square = square - 1; currentSum = currentSum / 100; // convert from cents to dollars System.out.println("The sum to be paid for " + square + " squares" + " is $" + currentSum + "."); } }