1 28 29 package example13; 30 31 public class Conversion 32 { 33 private Conversion () {} 34 35 public static String serializeDollarsCents(int cents) { 36 StringBuffer buff = new StringBuffer (); 37 buff.append(cents / 100); 38 int extra = cents % 100; 39 if (extra != 0) { 40 buff.append('.'); 41 if (extra < 10) { 42 buff.append('0'); 43 } 44 buff.append(extra); 45 } 46 return buff.toString(); 47 } 48 49 public static int deserializeDollarsCents(String text) { 50 int split = text.indexOf('.'); 51 int cents = 0; 52 if (split > 0) { 53 cents = Integer.parseInt(text.substring(0, split)) * 100; 54 text = text.substring(split+1); 55 } 56 return cents + Integer.parseInt(text); 57 } 58 59 public static String serializeIntArray(int[] values) { 60 StringBuffer buff = new StringBuffer (); 61 for (int i = 0; i < values.length; i++) { 62 if (i > 0) { 63 buff.append(' '); 64 } 65 buff.append(values[i]); 66 } 67 return buff.toString(); 68 } 69 70 private static int[] resizeArray(int[] array, int size) { 71 int[] copy = new int[size]; 72 System.arraycopy(array, 0, copy, 0, Math.min(array.length, size)); 73 return copy; 74 } 75 76 public static int[] deserializeIntArray(String text) { 77 int split = 0; 78 text = text.trim(); 79 int fill = 0; 80 int[] values = new int[10]; 81 while (split < text.length()) { 82 int base = split; 83 split = text.indexOf(' ', split); 84 if (split < 0) { 85 split = text.length(); 86 } 87 int value = Integer.parseInt(text.substring(base, split)); 88 if (fill >= values.length) { 89 values = resizeArray(values, values.length*2); 90 } 91 values[fill++] = value; 92 while (split < text.length() && text.charAt(++split) == ' '); 93 } 94 return resizeArray(values, fill); 95 } 96 } 97 | Popular Tags |