2

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 (" ")

4
  • if(Character.isDigit(str.charAt(0)) == 0) { return false; } this condition is weirdly stated. Why are you evaluating a boolean and an int? Commented Nov 10, 2016 at 3:39
  • Also, you should remove the break;, negate that first condition, and put the return false; inside it. Commented Nov 10, 2016 at 3: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. Commented Nov 10, 2016 at 3:44
  • 1
    possible duplicate at stackoverflow.com/questions/1102891/… Commented Nov 10, 2016 at 3:44

6 Answers 6

7

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

Sign up to request clarification or add additional context in comments.

Comments

4

Just check if Integer.parseInt throws exception or not.

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

1 Comment

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.
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.

4 Comments

in the checking logic, should handle hyphen - for negative value (and plus + for positive one)
@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
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 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.
1

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;.

2 Comments

Vote for handling empty string as OP want
This will return false positives if the number is bigger than "2,147,483,647"
0

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;
}

3 Comments

So... just str.matches("[0-9]+");?
Haha, yes, it's same. I just copy from the java API example
This will return false positives if the number is bigger than "2,147,483,647"
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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.