0

I need to parse string hex value to the Integer value. Like this:

String hex = "2A"; //The answer is 42  
int intValue = Integer.parseInt(hex, 16);

But when I insert an incorrect hex value (for example "LL") then I get java.lang.NumberFormatException: For input string: "LL" How I can avoid it (for example return 0)?

0

5 Answers 5

1

You can catch the exception and return zero instead.

public static int parseHexInt(String hex) {
    try {
        return Integer.parseInt(hex, 16);
    } catch (NumberFormatException e) {
        return 0;
    }
}

However, I recommend re-evaluating your approach, as 0 is a valid hex number as well, and doesn't signify invalid input such as "LL".

Sign up to request clarification or add additional context in comments.

Comments

1

For input string: "LL" How I can avoid it (for example return 0)?

Just catch the exception and assign zero to intvalue

int intValue;
try {
String hex = "2A"; //The answer is 42  
intValue = Integer.parseInt(hex, 16);
}
catch(NumberFormatException ex){
  System.out.println("Wrong Input"); // just to be more expressive
 invalue=0;
}

1 Comment

Note that you have to declare your variable intValue outside the try block. Scope matters.
1

Enclose it in a try catch block. That is how Exception Handling works: -

int intValue = 0;
try {
    intValue = Integer.parseInt(hex, 16);
} catch (NumberFormatException e) {
    System.out.println("Invalid Hex Value");
    // intValue will contain 0 only from the default value assignment.
}

Comments

0

Just catch the exception and set the default value. However, you need to declare the variable outside the try block.

int intValue;
try {
    intValue = Integer.parseInt(hex, 16);
} catch (NumberFormatException e) {
    intValue = 0;
}

If you need to set the value using an initializer expression (say, for a final variable), you'll have to package up the logic in a method:

public int parseHex(String hex) {
    try {
        return Integer.parseInt(hex, 16);
    } catch (NumberFormatException e) {
        return 0;
    }
}

// elsewhere...
final int intValue = parseHex(hex);

Comments

0

How I can avoid it (for example return 0)

Using a simple method which will return 0 in case a NumberFormatException occurrs

public int getHexValue(String hex){

    int result = 0;

    try {
        result = Integer.parseInt(hex, 16);
     } catch (NumberFormatException e) {
        e.printStackTrace();
    }
    return result;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.