有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么在将十六进制字符串格式化为三位数时会得到IllegalFormatConversionException?

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

在first pass函数中,我的代码段如下所示:

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

我知道这意味着出于某种原因,它不接受十六进制字符串。但我似乎不明白为什么不是十六进制字符串,我的意思是我用的是整数。toHexString()

任何帮助都将不胜感激,谢谢。如果这还不足以让您看到,那么如果您愿意,我可以发布更多的代码


共 (1) 个答案

  1. # 1 楼答案

    您不需要调用toHexString(),因为format()中的"X"将负责转换:

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