Saral Saxena
Saral Saxena

Reputation: 121

Expression to validate the required field

Below is the method to throw the exception if the amount is not integer or float but when I pass string forcefully it does not work , as in case of string it should throw the exception and make the valid as false but it still return the valid as true please advise what is wrong in my expression below

private boolean isAmount(String amount) {
    boolean isValid = true;
    try {
        if (amount.matches("[-+]?[0-9]*\\.?[0-9]+"))  {
            return isValid;     
        }
    }
    catch (NumberFormatException e) {
        isValid = false;
    }
    return isValid;
}

Upvotes: 2

Views: 90

Answers (3)

Samujeet Chakraborty
Samujeet Chakraborty

Reputation: 11

   // Try this one to check the output - running fine.... as per your needs

    private boolean isAmount(String amount) {
    boolean isValid = true;
    try {
           if (amount.matches("[-+]?[0-9]*\\.?[0-9]+"))  {
           isValid= true; 
}   
else
{
 isValid = false;
}

}catch (NumberFormatException e) {
    isValid = false;
    }
    return isValid;
    }

Upvotes: 1

Pete B.
Pete B.

Reputation: 3286

Your regex works just fine, it is the logic around it that is not working:

This will work:

private boolean isAmount(String amount) {
  if(amount == null) return false;
  if (amount.matches("[-+]?[0-9]*\\.?[0-9]+")) return true;
  return false;
}

Or something like this:

private boolean isAmount(String amount) {
  boolean ret = true;
  try {
    double val = Double.parseDouble(amount);
  } catch (NumberFormatException e) {
    ret = false;
  }
  return ret;
}

Upvotes: 3

xagyg
xagyg

Reputation: 9721

You are not trying to convert it anywhere, so no exception thrown. Just do this...

private boolean isAmount(String amount) {
    return amount.matches("[-+]?[0-9]*\\.?[0-9]+"));
}

Upvotes: 3

Related Questions