这是我要做的:
String raw = new String(node); // might be a better way to get a string from the chars
int slashPos = raw.indexOf('\\');
if(slashPos >= 0) {
String hex = raw.substring(slashPos + 1);
int value = Integer.parseInt(hex,16);
}
通过这种方式,我们不会对 2、3、4 或 100 位数字进行特殊封装(尽管我确信 100 位数字会引发异常 :-))。相反,我们将协议用作字符串中的“里程碑”,然后只接受斜线后面的所有内容都是十六进制字符串。
class HexParse {
private static class HexResult {
final boolean exists;
final int value;
HexResult(boolean e, int v) { exists = e; value = v; }
}
private final String raw;
private final HexResult result;
public HexParse(String raw) {
this.raw = raw;
int slashPos = raw.indexOf('\\');
boolean noSlash = slashPos < 0;
boolean noTextAfterSlash = slashPos > raw.length() - 2;
if(noSlash || noTextAfterSlash) {
result = new HexResult(false,0);
} else {
// throws exception if second part of string contains non-hex chars
result = new HexResult(true,Integer.parseInt(raw.substring(slashPos + 1),16));
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(raw).append(" ");
if(result.exists) {
sb.append("has hex of decimal value ").append(result.value);
} else {
sb.append("has no hex");
}
return sb.toString();
}
public static void main(String...args) {
System.out.println(new HexParse("test`hello")); // none
System.out.println(new HexParse("haha\\abcdef")); // hex
System.out.println(new HexParse("good\\f00d")); // hex
System.out.println(new HexParse("\\84b")); // hex
System.out.println(new HexParse("\\")); // none
System.out.println(new HexParse("abcd\\efgh")); //exception
}
}
c:\files\j>javac HexParse.java
c:\files\j>java HexParse
test`hello has no hex
haha\abcdef has hex of decimal value 11259375
good\f00d has hex of decimal value 61453
\84b has hex of decimal value 2123
\ has no hex
Exception in thread "main" java.lang.NumberFormatException: For input string: "e
fgh"
at java.lang.NumberFormatException.forInputString(NumberFormatException.
java:48)
at java.lang.Integer.parseInt(Integer.java:458)
at HexParse.<init>(HexParse.java:21)
at HexParse.main(HexParse.java: