Jo.P
Jo.P

Reputation: 1159

Comparison problems [.equals()] in java

I am trying to determine whether a string contains a positive int or not. My code is:

public void isInt(String str) throws NotIntException{
    String integer=str.replaceAll("\\d","");
    System.out.println(integer);
    if (!integer.equals("")){
        throw new NotIntException("Wrong data type-check fields where an integer"+
        " should be.");
    }//end if
    if (integer.equals("-")){
        System.out.println(integer);
        throw new NotIntException("Error-Can't have a negative count.");
    }//end if
}//end method

I am testing this with a string "-1", which should, after the replaceAll(), become "-". This should enter both if-statements. But it only enters the first. I tried it with the == comparison too, just in case, but it didn't work either. What's odd to me is that whether I look to fulfill the second if-statement's condition or to fulfill its negation [i.e., !integer.equals("-")], the program still doesn't enter the if....

Thanks, usually my comparison issues are just me missing something basic, but I really don't see anything here...

Upvotes: 0

Views: 365

Answers (4)

jlordo
jlordo

Reputation: 37813

My solution:

public static boolean isPositiveInt(String str) {
    try {
       int number = Integer.parseInt(str.trim());
       return number >= 0;
    } catch (NumberFormatException e) {
       return false;
    }
}

Upvotes: 1

Bohemian
Bohemian

Reputation: 424983

You approach is too complicated. I would keep it simple:

if (integer.startsWith("-")) {
    // it's a negative number
}

if (!integer.matches("^\\d+$")) {
    // it's not all-numbers
}

and forget the call to replaceAll()

Upvotes: 0

Name
Name

Reputation: 2045

If you want to simply read an int from a String, use Integer.parseInt(), although that would only work if you want to see if a string "is" an int, not contains one.

You could use a combination of Integer.parseInt() and a loop strategy to see if it contains an int fairly easily though, then just check if that is positive or not.

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213203

Since you are throwing an Exception in your first if, so, your 2nd if will not even be tested.

if (!integer.equals("")){
    throw new NotIntException("Wrong data type-check fields where an integer"+
    " should be.");
}

if (integer.equals("-")){
    System.out.println(integer);
    throw new NotIntException("Error-Can't have a negative count.");
}

If your code enters the first if, it will not execute further.


But, why are you using this approach for your problem.

You can easily use Integer.parseInt to check for valid integer. And then if it is valid, then test whether its less than 0. It would be far easier and readable.

Upvotes: 3

Related Questions