TheCompile
TheCompile

Reputation: 19

Can't figure out how to fix my code

Hi for the past few hours i have been trying to fix my code. The problem is that when I go to check if "" is an integer is returns true when it should be false. I know why this is happening, it is because it doesn't enter the for loop and returns true , but I can't seem to figure out how to make it return false for "". I can provide more info if needed.

public boolean isInteger(String str)
{
for (int x = 0, n = str.length(); x < n; x++)
{
  char c = str.charAt(x);
  if (c < '0' || c > '9') 
  {
    if (c != 0 || c != '-') 
    {
        return false;
    }
  }  
}    
return true;
}

Thank you for spending your time on trying to help me :)

Upvotes: 0

Views: 44

Answers (2)

Thomas
Thomas

Reputation: 388

You could check valid input (ie, a string with length = 0) and return false before you ever try the loop. You're correct, though, it's not entering the loop and just returning true.

--edit-- Something like

if (string == null) || (string.length() == 0){
     return false
}

Upvotes: 1

AdeelMufti
AdeelMufti

Reputation: 351

In your algorithm, an empty string will always return true. You just need to add a check:

if(str==null || str.length()==0) return false;

Alternatively, you can use this function:

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

}

Upvotes: 1

Related Questions