I have a string of various types including integers, *, +, and @. It is in a hashmap. When I am traversing the string, I want to be able to identify which parts are integers and which are not. For example, if I have "*12#", I want to be able to say if(string.substring(2,3)) is not an integer, return false.

Below, I am testing if converting the character into an integer will result in an error. However, this gives me a NumberFormatException.

//hm is hashmap
for(int i=hm.size()-1;i>=0;i--) {
            if(Integer.parseInt(hm.get(i))%1==0) {
                try {
                    System.out.println("integer");
                }
                catch(Exception e){
                    System.out.println("not integer");
                }
            }
        }

Here is the error log:

Exception in thread "main" java.lang.NumberFormatException: For input string: "-"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at Prefix.findValue(Prefix.java:32)
    at Prefix.makeHashMap(Prefix.java:27)
    at Prefix.<init>(Prefix.java:10)
    at Prefix.main(Prefix.java:45)

What is a better way of approaching this problem?

1 Answers

1
Carcigenicate On

The call to parseInt needs to be inside te try, and you should only be catching the exception that you intend to handle:

for(int i = hm.size() - 1; i >= 0; i--) {
    try {
        // Try to parse it
        String temp = Integer.parseInt(hm.get(i));
        System.out.println("integer");

    // And for best practice, specify the exact exception
    } catch(NumberFormatException e) {
        System.out.println("not integer");
    }
}