Why do I get IllegalFormatConversionException when formatting a hexadecimal string to three digits?
format, hex, java, string
Solution
You don't need to call `toHexString()` as the `"X"` in `format()` will take care of the conversion:
String.format("%03X", locCounter)
Problem
I am working on a class project where I have to build a two pass assembler for an instruction set we were looking at in class. In the first pass function, a segment of my code looks like this: ``` //If the fourth character is a comma, then it follows that the line contains a label. if (line.indexOf(',') == 3) { //Store symbol in address-symbol table together with value of location counter String symbolTableLine = line.substring(0,3) + " " + String.format("%03X", Integer.toHexString(locCounter)) + "\r\n"; symbolTable[symbolTablePos] = symbolTableLine; writerSymbTable.write(symbolTableLine); //Increment the location counter and the current position in symbol table locCounter++; symbolTablePos++; ``` My issue is with the following function call: ``` String.format("%03X", Integer.toHexString(locCounter)) ``` The goal for this is to convert the location counter to a hexadecimal string (such as "AA", "0", or "F") and add zeros as placeholders until the hexadecimal string is three digits long ("0AA", "000", "00F") The problem is that I am receiving this exception: ``` Exception in thread "main" java.util.IllegalFormatConversionException: x != java.lang.String ``` I know this means that it is not taking in a hexadecimal string for some reason. But I can't seem to figure out why that wouldn't be a hexadecimal string, I mean I'm using Integer.toHexString()... Any help would be appreciated, thanks. If this is not enough code for you to see, then I can post more of the code if you want.