Look-up Arrays
A Programming Pattern |
Prof. David Bernstein |
Computer Science Department |
bernstdh@jmu.edu |
private static final int[] NEW_NUMBERS = {-1, 1, 15, 16, 28, 35}; /** * Get the new exit number that corresponds to an old exit number. * Old exit numbers were consecutive. New exit numbers are based * on mileage markers. * * @param oldExitNumber The old exit number * @return The new exit number (or -1 if there was no such old exit number) */ public static int newExitNumberFor(int oldExitNumber) { if ((oldExitNumber < 1) || (oldExitNumber > 5)) { return -1; } else { return NEW_NUMBERS[oldExitNumber]; } }
private static final String[] NAMES = {"", "Willow Ave.", "Broad St.", "Downtown", "North End", "Lake Dr."}; /** * Get the name for an old exit number. * * @param oldExitNumber The old exit number * @return The name of the exit (or "") */ public static String exitNameFor(int oldExitNumber) { if ((oldExitNumber < 1) || (oldExitNumber > 5)) { return ""; } else { return NAMES[oldExitNumber]; } }
index = year - 2015;
private static final double[] SALES = { 107.2, 225.1, 189.9, 263.2}; /** * Get the annual sales revenues for a given year. * * @param year The year of interest * @return The sales revenue in $100,000 (or 0.0) */ public static double sales(int year) { if ((year < 2015) || (year >= 2019)) { return 0.0; // No sales } else { int index; index = year - 2015; return SALES[index]; } }
private static final char[] GRADES = { 'F', 'F', 'F', 'F', 'F', 'F', 'D', 'C', 'B', 'A', 'A'}; /** * Determine the letter grade that corresponds to a number grade. * * @param numberGrade The numeric grade * @return The letter grade */ public static char letterGrade(int numberGrade) { int index; index = numberGrade / 10; return GRADES[index]; }
private static final char[] STATUS = {'F', 'P'}; /** * Determine if a grade is passing or failing. * * @param grade The grade * @return 'F' or 'P' */ public static char passFail(double grade) { int index; index = (int) (grade / 60.0); return STATUS[index]; }
private static final double[] POP = { 3.9, 5.2, 7.2, 9.6, 12.9, 17.1, 23.1, 31.4, 38.6, 49.4, 63.0, 76.2, 92.2, 106.0, 123.2, 132.2, 151.3, 179.3, 203.2, 226.5, 248.7, 281.4, 308.7}; /** * Get the US population for the previous census year. * * @param year The year of interest * @return The population for the previous census year (or -1) */ public static double population(int year) { int index; if ((year < 1790) || (year >= 2020)) { return -1.0; } else { index = (year - 1790) / 10; return POP[index]; } }