1

Instructions: Given a string, determine if it is an integer. For example the string “123” is an integer, but the string “hello” is not.

It is an integer if all of the characters in the string are digits.

Return true if it is an integer, or false if it is not.

Hint: There is a method Character.isDigit() that takes a char as an argument and returns a boolean value.

What I have so Far:

public boolean isInteger(String str) {
    if(Character.isDigit(str.charAt(0)) == 0) {
        return false;
    }
    for (int i = 0; i < str.length(); i++) {
        if(Character.isDigit(str.charAt(i))) {
            break;
        } else {
            return false;
        }
    }
    return true;
}

I'm having an issue with returning a boolean value for the string "101" and no string at all (" ")

zyexal
  • 1,570
  • 16
  • 23
Harry You
  • 87
  • 2
  • 3
  • 11
  • `if(Character.isDigit(str.charAt(0)) == 0) { return false; }` this condition is weirdly stated. Why are you evaluating a `boolean` and an `int`? – Hypnic Jerk Nov 10 '16 at 03:39
  • Also, you should remove the `break;`, negate that first condition, and put the `return false;` inside it. – Hypnic Jerk Nov 10 '16 at 03:40
  • for the "if(Character.isDigit(str.charAt(0)) == 0) { return false; }", I was trying to make the code return false if nothing was put into the string. Also, I tried negating the first condition which made my "101" boolean string correct, but it ended up making all the other return values incorrect. – Harry You Nov 10 '16 at 03:44
  • 1
    possible duplicate at http://stackoverflow.com/questions/1102891/how-to-check-if-a-string-is-numeric-in-java – Ye Win Nov 10 '16 at 03:44

6 Answers6

8

You could use a regular expression.

return str.matches("\\d+");

won't work for negative numbers, though.

You could also use Integer.parseInt and catch the NumberFormatException and return true/false accordingly.

Or, you should not break the first digit you find, as you need to check all characters, only until you find one that is not a digit. Again, this does not capture negative numbers

public boolean isInteger(String str) {
    if(str == null || str.trim().isEmpty()) {
        return false;
    }
    for (int i = 0; i < str.length(); i++) {
        if(!Character.isDigit(str.charAt(i))) {
            return false;
        } 
    }
    return true;
}

Personally, option 2 is the best, but your instructions seem to imply that you need to iterate over character values

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
3

Just check if Integer.parseInt throws exception or not.

try {
    Integer.parseInt(string);
} catch (NumberFormatException e) {
    return false;
}
return true;
riversun
  • 758
  • 8
  • 12
  • The program I'm using is a very limited compiler with the purpose of teaching people how to do particular methods of Java in each chapter. It (sadly) cannot use the .parseInt because the current lesson does not teach it. – Harry You Nov 10 '16 at 03:48
2

You are close, but have mixed up logic. I'll go through it with you now.

if(Character.isDigit(str.charAt(0)) == 0) {
    return false;
}

I'm not sure what this above statement if trying to test. I see that you are checking if the 0 index is a digit, but then you compare it to 0. Even if this was written correctly, this statement can be removed because you are about to iterate through the string. After reading your comment it seems that it was meant to check for null or empty string. In which case you may want to test the string directly.

if(str == null || str.isEmpty())
    return false;

for (int i = 0; i < str.length(); i++) {
    if(Character.isDigit(str.charAt(i))) {
        break;
    }
     else {
        return false;
    }
}
return true;

The above break; does not do what I think you think it does. break; will exit out of the for loop, thus only checking the first character. I suggest rewriting this if-else to get rid of the else and negate your isDigit method. See my code below.

for(int i = 0;i < str.length();i++){
    if(!Character.isDigit(str.charAt(i))
        return false;
}
return true;

You only want to return false if the character is not a digit.

Hypnic Jerk
  • 1,192
  • 3
  • 14
  • 32
  • in the checking logic, should handle hyphen - for negative value (and plus + for positive one) – kidnan1991 Nov 10 '16 at 04:24
  • @kidnan1991 I don't believe OP is worried about `+` or `-`. Since OP was pointed in the direction of `Character.isDigit()`, `+` and `-` are not digits and therefore will `return false` if input – Hypnic Jerk Nov 10 '16 at 04:29
  • I got your point. OP does not care about the sign (- or +0). About your solution, it it not correct if the prefix is empty (OP want it to be false). So, firstly, trimmed the string => Check size before any process – kidnan1991 Nov 10 '16 at 04:58
  • @kidnan1991 I considered trimming the string, but I don't think this will matter. I could add another part to the first `if` statement, but if the `string` only has a space in it, then it is not a digit and will exit anyways. – Hypnic Jerk Nov 10 '16 at 21:03
2

All the above solution seems correct to me but I would like to give one more solution to this problem. You can check this using ASCII values too:

private Boolean IsInteger(String str)
{
   int length = str.length(),c=0;
   if(length==0)
      return false;
   for(int i=0;i<length; i++)
   {
      c = (int)str.charAt(i)-48;
      if(!(c>=0 && c<10))
         return false;
   }
  return true;
}

I think My solution is much better because it used less number of library functions per iterations.

I am not checking for negative values because in the questions you have specified that the string is Integer if all the characters are digits. If you want to check negative numbers you can do it by adding one condition in i==0;.

Denis
  • 1,219
  • 1
  • 10
  • 15
1

I suggest using regex to identify integer.

Like this

public boolean isInteger(String str){
  Pattern p = Pattern.compile("[0-9]+");
  Matcher m = p.matcher(str);
  boolean b = m.matches();
  return b;
}
hk_csl0615
  • 11
  • 2
0

In java, you can use this regex pattern : It will filter either negative or positive value

private static final String NUMBER_REGEX = "(^\\d++)|(^[\\-]{1}\\d++)";
private static final Pattern NUMBER_PATTERN = Pattern.compile(NUMBER_REGEX);
final Matcher matcher = NUMBER_PATTERN.matcher(inputString);
if(matcher.find()) {
// If matcher => parse the value
final String sNumber = matcher.group();
final int value = Integer.parseInt(sNumber);
} else {
// Not matching
}
kidnan1991
  • 366
  • 2
  • 12