/** * This class contains static methods used to anglicize integers in the * range 1..999,999. Method anglicize contains the solution. * * This is great class to see how preconditions work. */ public class Anglicize { /** * Returns: English equivalent of n. * Precondition: 0 < n < 1,000,000. * Examples: * 3: "three" * 45: "forty five" * 100: "one hundred" * 127: "one hunded twenty seven" * 1001: "one thousand one" * 999099: "nine hundred ninety thousand ninety nine */ public static String anglicize(int n) { if (n < 1000) { return anglicize1000(n) ; } // n >= 1000 return anglicize1000(n/1000) + " thousand"+ (n % 1000 == 0 ? "" : " " + anglicize1000(n % 1000)); } /** * Yields: English equiv of n. * Precondition: n in 1..999 */ public static String anglicize1000(int n) { if (n < 20) { return anglicize1to19(n); } // n >= 20 if (n < 100) { return anglicize20to99(n) ; } // n >= 100 return anglicize100to999(n) ; } /** * Returns: English equiv of n. * Precondition: n in 1..19 */ public static String anglicize1to19(int n) { if (n == 1) { return "one"; } if (n == 2) { return "two"; } if (n == 3) { return "three"; } if (n == 4) { return "four"; } if (n == 5) { return "five"; } if (n == 6) { return "six"; } if (n == 7) { return "seven"; } if (n == 8) { return "eight"; } if (n == 9) { return "nine"; } if (n == 10) { return "ten"; } if (n == 11) { return "eleven"; } if (n == 12) { return "twelve"; } if (n == 13) { return "thirteen"; } if (n == 14) { return "fourteen"; } if (n == 15) { return "fifteen"; } if (n == 16) { return "sixteen"; } if (n == 17) { return "seventeen";} if (n == 18) { return "eighteen"; } return "nineteen"; } /** * Returns: English equiv of n. * Precondition: n in 20..99 */ public static String anglicize20to99(int n) { return tens(n/10) + (n % 10 == 0 ? "" : " " + anglicize1to19(n % 10)); } /** * Returns: English equiv of n. * Precondition: n in 100..999 */ public static String anglicize100to999(int n) { // Anglicize the first three digits int hundreds = n % 100; String suffix = ""; if (hundreds > 0 && hundreds < 20) { suffix = " "+anglicize1to19(hundreds); } if (hundreds > 20) { suffix = " "+anglicize20to99(hundreds); } return anglicize1to19(n/100) + " hundred" + suffix; } /** * Returns: tens-word for n * Precondition: n in 2..9 */ public static String tens(int n) { if (n == 2) { return "twenty"; } if (n == 3) { return "thirty"; } if (n == 4) { return "forty"; } if (n == 5) { return "fifty"; } if (n == 6) { return "sixty"; } if (n == 7) { return "seventy";} if (n == 8) { return "eighty"; } return "ninety"; } }