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

4

我正在做一个课程项目,需要为我们在课堂上学习的指令集构建一个两遍汇编器。

在第一遍扫描函数中,我的代码段看起来像这样:

        //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++;

我的问题出现在以下函数调用中:

String.format("%03X", Integer.toHexString(locCounter))

这个目标是将位置计数器转换为十六进制字符串(例如“AA”,“0”或“F”),并添加零作为占位符,直到十六进制字符串为三位数为止(“0AA”,“000”,“00F”)

问题在于我收到了以下异常:

 Exception in thread "main" java.util.IllegalFormatConversionException: x != java.lang.String

我知道这意味着某些原因导致它没有接受十六进制字符串。但我似乎无法弄清楚为什么那不是一个十六进制字符串,我使用的是Integer.toHexString()...
如果需要更多代码,请告诉我。谢谢您的帮助。

你意识到 Integer.toHexString() 返回一个字符串,而你试图将其格式化为数字,这不再是一个数字,因此,%x 不再有效。 - Badr Ghatasheh
1个回答

7
您不需要调用toHexString(),因为format()中的"X"会处理转换:
String.format("%03X", locCounter)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接