Integer.decode(String s)

Raj*_*hna 2 java

class Test{

    public static void main(String Args[]){

        Integer x;
        x = Integer.decode("0b111");
        System.out.println(x);
    }
}
Run Code Online (Sandbox Code Playgroud)

对于二进制的前缀0和前缀为0的八进制,这不起作用.正确的方法是什么?

Jon*_*eet 5

查看文档Integer.decode,我看不到二进制文件应该工作的迹象.八进制应该工作,前缀只有0:

System.out.println(Integer.decode("010")); // Prints 8
Run Code Online (Sandbox Code Playgroud)

您可以像这样处理"0b"的二进制指示符:

int value = text.toLowerCase().startsWith("0b") ? Integer.parseInt(text.substring(2), 2)
                                  : Integer.decode(text);
Run Code Online (Sandbox Code Playgroud)

完整示例代码显示15的二进制,八进制,十进制和十六进制表示:

public class Test {
    public static void main(String[] args) throws Exception {
        String[] strings = { "0b1111", "017", "15", "0xf" };
        for (String string : strings) {
            System.out.println(decode(string)); // 15 every time
        }
    }

    private static int decode(String text) {
        return text.toLowerCase().startsWith("0b") ? Integer.parseInt(text.substring(2), 2)
                                     : Integer.decode(text);
    }

}
Run Code Online (Sandbox Code Playgroud)