0

I was trying to write a piece of code to test if a string contains an integer. I am aware of the try catch solution, but i have read it becomes bad if you call the method from other classes. What I have read is that the method will show the error, but the main of the class calling it will keep running anyway. Therefore, I was trying to do it manually. My problem is that i am able to assess that the string is not empty and that all the characters in the string are digits, but I can't find a way to verify whether the number is too big to be sorted in an integer. Point is, i have found on stackoverflow many similar topics, but noone solve this problem without try catch. Here is my method.

// INTEGER VERIFICATION
public static boolean isInteger (String str_input){
    int number_of_digits = 0;
    if (str_input.isEmpty()) {
        JOptionPane.showMessageDialog(null, "No input inserted", "Error", JOptionPane.ERROR_MESSAGE);
        return false;
    }
    for (char c : str_input.toCharArray()){
        if(Character.isDigit(c)){
            number_of_digits++;
        }
    }
    if (number_of_digits == str_input.length()){
        return true;
    }
    else {
        JOptionPane.showMessageDialog(null, "The input is not an integer", "Error", JOptionPane.ERROR_MESSAGE);
        return false;
    }
}

Thanks in advance for your help!

Pezze
  • 741
  • 1
  • 7
  • 14
  • 5
    using the try catch is the simplest way, IMO. Otherwise you'll have to compare with Integer.MAX_VALUE and Integer.MIN_VALUE and against null – Leo Aug 03 '14 at 21:49
  • 1
    I think your assumptions are flawed. There is nothing wrong with the try catch approach, other than being slow. – Jeremy Aug 03 '14 at 21:49
  • 2
    @Jeremy And I am not sure it is actually going to be slower than the checks being performed here. – Brett Okken Aug 03 '14 at 21:50
  • The only reason the try-catch solution won't tell the calling class is if y never re-throw the exception, or otherwise provide feedback from the method about the suitability often value. Having said that, you should not be making branching decisions with exceptions – MadProgrammer Aug 03 '14 at 21:51
  • 1
    @Jeremy Considering this code is working with a GUI the speed of exception handling will be instantaneous in comparison to user perception. – Dunes Aug 03 '14 at 21:57
  • `Integer.parseInt` does exactly what you are willing to do, and it does it well. It throws an exception if the input doesn't qualify as an integer, without introducing any side effect. In case of doubt check the source : it is not that long/complicated, and it is really robust (https://android.googlesource.com/platform/libcore/+/refs/heads/master/luni/src/main/java/java/lang/Integer.java). – Shlublu Aug 03 '14 at 21:59
  • There is a [regex solution to this problem](http://stackoverflow.com/a/20793792/256196) (almost a duplicate) – Bohemian Aug 03 '14 at 23:34

3 Answers3

2

I think the best way to do this is as pointed by Leo in the comments.

public static boolean isInteger(final String strInput) {
    boolean ret = true;
    try {
        Integer.parseInt(strInput);
    } catch (final NumberFormatException e) {
        ret = false;
    }
    return ret;
}

Also I suggest you separate the GUI part from the checking method, let the caller decide what to do if false (for example, maybe in some situations you want to check if it's an integer but don't show the dialog).

m0skit0
  • 25,268
  • 11
  • 79
  • 127
0

You could modify your method to make sure the number fits within an int.

It can be done by parsing the input as long, and checking against the range of int numbers.

// INTEGER VERIFICATION
public static boolean isInteger (String str_input){
    int number_of_digits = 0;
    if (str_input.isEmpty()) {
        JOptionPane.showMessageDialog(null, "No input inserted", "Error", JOptionPane.ERROR_MESSAGE);
        return false;
    }
    for (char c : str_input.toCharArray()){
        if(Character.isDigit(c)){
            number_of_digits++;
        }
    }
    if (number_of_digits == str_input.length()){
        if (str_input.length > 15) // arbitrary length that is too long for int, but not too long for long
            return false;
        long number = Long.parseLong(str_input);
        if (number > Integer.MAX_VALUE || number < Integer.MIN_VALUE)
           return false;
        else
           return true;
    }
    else {
        JOptionPane.showMessageDialog(null, "The input is not an integer", "Error", JOptionPane.ERROR_MESSAGE);
        return false;
    }
}

BTW, if you allow negative inputs, you should change your check to allow '-' as the first character.

That said, I agree with all the comments that say you'd be better off to just call Integer.parseInt() and catch the exception.

Eran
  • 387,369
  • 54
  • 702
  • 768
0

How about using Regex

 -?\\d+(\\.\\d+)? which accept negative and decimal numbers 

Source: http://www.vogella.com/tutorials/JavaRegularExpressions/article.html

 public static boolean isNumeric(String str) {
        return str.matches("-?\\d+(\\.\\d+)?");  
    }
Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58