// ShowColorScale.java // A solution to CS 10 assignment 2, part 2, Fall 2008 // cmc 8/14/08 import java.awt.Color; import java.util.Scanner; public class ShowColorScale { private static Scanner input; // used in all methods public static void main(String[] args) { input = new Scanner(System.in); // let utility method get the first and last colors Color c1 = getColor("First Color"); Color c2 = getColor("Last Color"); // get the number of levels - insure an int >= 2 int levels = 0; while (levels < 2) { System.out.print("Enter number of levels >= 2: "); if (input.hasNextInt()) { levels = input.nextInt(); if (levels < 2) { System.err.println("entered < 2: " + levels); levels = 0; } } else if (input.hasNext()) { String junk = input.next(); System.err.println("entered non-int: " + junk); } } // create color scale, get array of colors, and display ColorScale scale = new ColorScale(c1, c2, levels); Color[] colors = new Color[scale.size()]; for (int i=0; i < scale.size(); i++) colors[i] = scale.get(i); CS10Display.show(colors); } // utility gets a valid color from the user private static Color getColor(String prompt) { final Color[] stockColors = { Color.BLACK, Color.BLUE, Color.CYAN, Color.DARK_GRAY, Color.GRAY, Color.GREEN, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE, Color.PINK, Color.RED, Color.WHITE, Color.YELLOW }; final String[] stockNames = { "BLACK", "BLUE", "CYAN", "DARK_GRAY", "GRAY", "GREEN", "LIGHT_GRAY", "MAGENTA", "ORANGE", "PINK", "RED", "WHITE", "YELLOW" }; Color result = null; while (result == null) { System.out.println("Select " + prompt + " by number:"); for (int i=0; i < stockNames.length; i++) System.out.printf(" %d: %s%n", i + 1, stockNames[i]); System.out.printf(" %d: %s%n", stockNames.length + 1, "Other"); if (input.hasNextInt()) { int i = input.nextInt() - 1; if (i >= 0 && i < stockNames.length) result = stockColors[i]; else if (i == stockNames.length) result = new Color(get("red"), get("green"), get("blue")); else System.err.println("no such choice: " + (i + 1)); } else if (input.hasNext()) System.err.println("choice not int: " + input.next()); } return result; } // utility used by getColor to get int value in proper range from user private static int get(String name) { int result = -1; while (result < 0 || result > 255) { System.out.printf("Enter amount of %s (0 to 255): ", name); if (input.hasNextInt()) { result = input.nextInt(); if (result < 0 || result > 255) { System.err.println("amount out of range"); result = -1; } } else if (input.hasNext()) System.err.println("amount not int: " + input.next()); } return result; } }