0

I know this question was posted a lot and I checked some solutions but none were working perfectly for me.

What I want is to check whether a Stringinput in a TextField is valid or not. Valid entries are only positive integers, in other words everything that is >=0 and an integer.

I tried a solution something like this that I found:

try {
    int input = Integer.valueOf(fieldwaitAfterAction.getText());
    if(input < 0)) {
        validInput = false; 
    } else { 
        validInput = true; 
    }
} catch(NumberFormatException e) {
    validInput = false;
}

Works for most of the wrong patterns fine, but if I enter something like '+0' or '-0' it passes through which shouldn't be actually the case. So I want a pure integer number without any characters at the beginning, in between or at the end.

What would the best solution be for this problem?

Thanks a lot!

Shar1er80
  • 9,001
  • 2
  • 20
  • 29
r.valbo
  • 25
  • 6
  • @tim this one isn't working for me, don't know why. met regex but don't know what the correct 'formula' would be to cover every character and pattern – r.valbo Jul 07 '15 at 20:27

7 Answers7

2
public static boolean checkForDigits(final String toCheck){
    boolean flag = true;
    char[] toCheckArray = toCheck.toCharArray();
    for(int index=0; index < toCheckArray.length, flag==true; index++){
        if( ! ( ( (int)toCheckArray[index] > 47 ) && ( (int)toCheckArray[index] < 58 ) ) ){
            flag = false;
        }
    }
    return flag;
}

There you go. It returns true if all are digits, false if it does not. It is O(n) time worst case. < O(n) if it detects anything other than a digit.

Charles Staal
  • 338
  • 1
  • 14
  • ey Charles... like you idea too.. but i should do this inside the loop `flag= ( ! ( ( (int)toCheckArray[index] > 47 ) && ( (int)toCheckArray[index] < 58 ) ) )`. Assign the boolean result directly to the variable ;), is more direct, don't you think so? – Victor Jul 07 '15 at 20:45
  • Almost right, except make a special case for the first character to check if it is 0. If it is, and the string contains anything else, this is invalid. – Orch Jul 07 '15 at 20:47
  • Victor, it is not. I don't want to waste time assigning a value when it's not needed. I honestly should have just put return false instead of using a flag at all. Orch, he never specified that case. All integers are valid and 024 is still an integer. – Charles Staal Jul 07 '15 at 23:00
2

I think you forgot to put = to.If i understood your question correctly this should fix your problem:

try{
                String input_string=fieldwaitAfterAction.getText()

                int input = Integer.valueOf(input_string);
                if(input <= 0)){
                    validInput = false; 

                }
                else{ validInput = true; }
                }
                catch(NumberFormatException e){
                    validInput = false;
}
Nitesh Singh
  • 789
  • 5
  • 24
2

You can use Regex ^\d+$ to check if a input contains only positive number.

^ assert position at start of the string
\d+ match a digit [0-9]
    Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
$ assert position at end of the string

In Java code:

String[] arr = { "-123", "123a", "0", "123" };
String regex = "^\\d+$";
for (String str : arr) {
  Matcher matcher = Pattern.compile(regex).matcher(str);
  if (matcher.find())
    System.out.println("String " + str + " is a positive number.");
  else 
    System.out.println("String " + str + " is NOT a positive  number.");
}

prints

String -123 is NOT a positive number.
String 123a is NOT a positive number.
String 0 is a positive number.
String 123 is a positive number.
MaxZoom
  • 7,619
  • 5
  • 28
  • 44
0

For me, this always do the magic....

  try {
    Integer.parseInt(theStringToEval);
    // is this line is reach.. it is a int
  }
  catch (NumberFormatException e){
    // is the flow goes here
  }

But it allows integer with signs... You could create a method for your convenience that hide this implementation details and add the check for the signs in there...

  public static boolean isPlainInteger (String string) {
    if (string.startsWith("-") || string.startsWith("+")) {
      return false;
    }

    try {
      Integer.parseInt(string);
      return true;
    }
    catch (NumberFormatException e){
      return false;
    }
  }

And you can achieve it through regex too.... perhaps this one could help.

 private static Pattern plainIntegerPattern = Pattern.compile("\\d+");
 public static boolean isPlainInteger (String string) {
    return plainIntegerPattern.matcher(string).matches();
 }

Hope it helps.

Victor
  • 3,841
  • 2
  • 37
  • 63
0

Integer.ValueOf allows + ans - signs. As per javadoc

...The characters in the string must all be digits of the specified radix (as determined by whether java.lang.Character.digit(char, int) returns a nonnegative value), except that the first character may be an ASCII minus sign '-' to indicate a negative value or an ASCII plus sign '+' to indicate a positive value

So Your code will break for any value having + followed by an integer and also +0 and -0 as both of them will result as 0. I'll give solution using regex.

String str = fieldwaitAfterAction.getText();
if (str == null) {
    retrun false;
}
String regex = "^(\\d+)$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
if (matcher.matches()) {
    int val = Integer.valueOf(matcher.group(0));
    if (val > 0) {
        return true;
    }
}
retrun false;

This way you could handle situation like 088 not being a valid input to you by using reges ^[^0](\\d+)$.

barunsthakur
  • 1,196
  • 1
  • 7
  • 18
0

Checks if the given input is a integer number, not a valid Java Integer (Integer.MAX_VALUE).

validInput = fieldwaitAfterAction.getText().length > 0
                &&  fieldwaitAfterAction.getText().matches("[0-9]+");
Ezequiel
  • 3,477
  • 1
  • 20
  • 28
0

You can use a simple regexp, like "(^0|[1-9]*\d)$". This allows you to put 0 or any positive integer.

fieldwaitAfterAction.getText().matches("(^0|[1-9]*\\d)$") 

Remember that using regexp like \d+ won't work, because it will accept strings like "001243"

bart.s
  • 688
  • 5
  • 12