将十六进制字符串格式化为三位数时,为什么会出现IllegalFormatConversionException?

Sam*_*ons 3 java string format hex

我正在进行一个类项目,我必须为我们在课堂上看到的指令集构建一个两遍汇编程序.

在第一个传递函数中,我的代码段看起来像这样:

        //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++;
Run Code Online (Sandbox Code Playgroud)

我的问题是以下函数调用:

String.format("%03X", Integer.toHexString(locCounter))
Run Code Online (Sandbox Code Playgroud)

这样做的目的是将位置计数器转换为十六进制字符串(例如"AA","0"或"F")并将零添加为占位符,直到十六进制字符串为三位数字("0AA","000" ","00F")

问题是我收到了这个例外:

 Exception in thread "main" java.util.IllegalFormatConversionException: x != java.lang.String
Run Code Online (Sandbox Code Playgroud)

我知道这意味着由于某种原因它没有接受十六进制字符串.但我似乎无法弄清楚为什么那不是十六进制字符串,我的意思是我正在使用Integer.toHexString()...

任何帮助将不胜感激,谢谢.如果这个代码不够用,那么我可以根据需要发布更多代码.

NPE*_*NPE 6

您无需打电话,toHexString()因为"X"in format()将负责转换:

String.format("%03X", locCounter)
Run Code Online (Sandbox Code Playgroud)