public class GenericMappingArraysSolution
1: //GenericMappingArraysSolution.java
3: import java.util.Scanner;
5: public class GenericMappingArraysSolution
6: {
7: public static <MapType extends Comparable<MapType>>
8: MapType getMapping
9: (
10: MapType mapMe,
11: MapType[] mappings
12: )
13: {
14: MapType result;
15: int i;
16: int len;
17: boolean keepLooking;
19: result = mapMe;
20: len = mappings.length;
21: keepLooking = true;
23: System.out.println();
24: System.out.print("Mapping range: ");
25: for (i = 0; i < len; ++i)
26: {
27: System.out.print(mappings[i] + " ");
28: }
29: System.out.println();
31: i = 0; // Restart counting
32: while ((i < len) && keepLooking)
33: {
34: if (mapMe.compareTo(mappings[i]) <= 0)
35: {
36: result = mappings[i];
37: keepLooking = false;
38: }
39: else
40: {
41: ++i;
42: }
43: }
44: System.out.println(mapMe + " is mapped to " + result);
46: return result;
47: }
49: // ***********************************************************************
51: public static void main(String [] args)
52: {
53: Scanner scnr = new Scanner(System.in);
55: // Declare various types to use to call getMapping
57: Integer mapInt;
58: Integer mapIntResult;
59: Integer [] mapIntMappings = { 100, 200, 300, 400, 500, 600 };
61: Double mapDouble;
62: Double mapDoubleResult;
63: Double [] mapDoubleMappings = { -12.0, -6.0, 0.0, 6.0, 12.0 };
65: String mapString;
66: String mapStringResult;
67: String [] mapStringMappings = { "A", "E", "M", "S", "W", "Z" };
68: String absorbInput; // To read a string after a number
70: // Get values to map, from user input
72: System.out.print("\nEnter an integer value to map: ");
73: mapInt = scnr.nextInt();
74: mapIntResult = getMapping(mapInt, mapIntMappings);
76: System.out.print("\nEnter a double value to map: ");
77: mapDouble = scnr.nextDouble();
78: mapDoubleResult = getMapping(mapDouble, mapDoubleMappings);
80: absorbInput = scnr.nextLine(); // Absorb the <Enter> from integer input
81: System.out.print("\nEnter a string value to map: ");
82: mapString = scnr.nextLine();
83: mapStringResult = getMapping(mapString, mapStringMappings);
84: }
85: }