1 58 package org.krysalis.barcode.tools; 59 60 66 public class Length { 67 68 private double value; 69 private String unit; 70 71 76 public Length(double value, String unit) { 77 this.value = value; 78 this.unit = unit.toLowerCase(); 79 } 80 81 86 public Length(String text, String defaultUnit) { 87 parse(text, defaultUnit); 88 } 89 90 94 public Length(String text) { 95 this(text, null); 96 } 97 98 103 protected void parse(String text, String defaultUnit) { 104 final String s = text.trim(); 105 if (s.length() == 0) { 106 throw new IllegalArgumentException ("Length is empty"); 107 } 108 StringBuffer sb = new StringBuffer (s.length()); 109 int mode = 0; 110 int i = 0; 111 while (i < s.length()) { 112 char c = s.charAt(i); 113 114 if (mode == 0) { 115 if (Character.isDigit(c) || c == '.' || c == ',') { 117 if (c == ',') { 118 c = '.'; 119 } 120 sb.append(c); 121 i++; 122 } else { 123 this.value = Double.parseDouble(sb.toString()); 124 sb.setLength(0); 125 mode = 1; 126 } 127 } else if (mode == 1) { 128 if (Character.isWhitespace(c)) { 130 i++; 131 continue; 132 } 133 mode = 2; 134 } else if (mode == 2) { 135 if (!Character.isWhitespace(c)) { 137 sb.append(c); 138 i++; 139 } else { 140 break; 142 } 143 144 } 145 } 146 if (mode == 0) { 147 this.value = Double.parseDouble(sb.toString()); 148 mode = 1; 149 } 150 if (mode != 2) { 151 if ((mode > 0) && (defaultUnit != null)) { 152 this.unit = defaultUnit.toLowerCase(); 153 return; 154 } 155 throw new IllegalArgumentException ("Invalid length specified. " 156 + "Expected '<value> <unit>' (ex. 1.7mm) but got: " + text); 157 } 158 this.unit = sb.toString().toLowerCase(); 159 } 160 161 165 public String getUnit() { 166 return this.unit; 167 } 168 169 173 public double getValue() { 174 return this.value; 175 } 176 177 181 public double getValueAsMillimeter() { 182 if (this.unit.equals("mm")) { 183 return this.value; 184 } else if (this.unit.equals("cm")) { 185 return this.value * 10; 186 } else if (this.unit.equals("pt")) { 187 return UnitConv.pt2mm(this.value); 188 } else if (this.unit.equals("in")) { 189 return UnitConv.in2mm(this.value); 190 } else { 191 throw new IllegalStateException ("Don't know how to convert " 192 + this.unit + " to mm"); 193 } 194 } 195 196 197 public String toString() { 198 return getValue() + getUnit(); 199 } 200 201 } 202 | Popular Tags |