Search code examples
javastringnumber-formattingnumberformatexception

Java: formatting numbers error?


I am encountering a problem regarding a class which converts number formats with String input and output:

public class Conversion{

static int result;

public static String fromHexToDec (String clientInput) {
    result= Integer.parseInt(clientInput, 10);
    return Integer.toString(result);
}

public static String fromDecToHex (String clientInput) {
    result= Integer.parseInt(clientInput, 16);
    return Integer.toString(result);
}

public static String fromOctTo4 (String clientInput) {
    result= Integer.parseInt(clientInput, 4);
    return Integer.toString(result);
}

public static String from4ToOct(String clientInput) {
    result= Integer.parseInt(clientInput, 8);
    return Integer.toString(result);
}

public static String formBinToDec(String clientInput) {
    result= Integer.parseInt(clientInput, 10);
    return Integer.toString(result);
}

public static String fromDecToBin(String clientInput) {
    result= Integer.parseInt(clientInput, 2);
    return Integer.toString(result);
}

public static String from5To7(String clientInput) {
    result= Integer.parseInt(clientInput, 7);
    return Integer.toString(result);
}

public static String from7To5(String clientInput) {
    result= Integer.parseInt(clientInput, 5);
    return Integer.toString(result);
}

}

I am receiving this error trying to run fromHexToDec in the the main method:

Exception in thread "main" java.lang.NumberFormatException: For input string: "C"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Konverzija.fromHexToDec(Conversion.java:9)
at Test.main(Test.java:5)

Can somebody help, please?


Solution

  • Because

    public static String fromHexToDec (String clientInput) {
        result= Integer.parseInt(clientInput, 10);
        return Integer.toString(result);
    }
    

    is passing radix 10 to parseInt() (and that's not valid in decimal). Use 16 like

    public static String fromHexToDec (String clientInput) {
        result= Integer.parseInt(clientInput, 16);
        return Integer.toString(result);
    }
    

    And fromDecToHex should probably be

    public static String fromDecToHex(String clientInput) {
        int result = Integer.parseInt(clientInput, 10);
        return Integer.toString(result, 16);
    }
    

    or

    public static String fromDecToHex(String clientInput) {
        int result = Integer.parseInt(clientInput);
        return String.format("%02X", result);
    }
    

    the second has the potential advantage of being zero filled.