Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's what I would do:</p> <pre><code>String raw = new String(node); // might be a better way to get a string from the chars int slashPos = raw.indexOf('\\'); if(slashPos &gt;= 0) { String hex = raw.substring(slashPos + 1); int value = Integer.parseInt(hex,16); } </code></pre> <p>In this manner, we're not special casing anything for 2, 3, 4, or 100 digits (although I'm sure 100 digits would throw an exception :-) ). Instead, we're using the protocol as a 'milestone' in the string, and then just accepting that everything after the slash is the hex string.</p> <pre><code>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 &lt; 0; boolean noTextAfterSlash = slashPos &gt; 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&gt;javac HexParse.java c:\files\j&gt;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.&lt;init&gt;(HexParse.java:21) at HexParse.main(HexParse.java: </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload