Comparing two strings for "greater than" 0 ".. and NULL"

I'm trying to get through the strict Java methods and operators, but now, trying to “translate” part of the PHP code to Java (Android), I'm a little stuck.

In PHP:

if ($row['price']>'0'){
  (.. do something if price is defined - and higher than zero ..)
}

The problem is that $ row ['price'] can be empty (in Java: null?) Or contain '0' (zero). But how can I encode this in Java in a smart and not too complicated way?

+3
source share
2 answers

Assuming you got a price line at a variable price

String price = <get price somehow>;    
try {
    if (price != null && Integer.valueOf(price) > 0) {
        do something with price...
    }
} catch (NumberFormatException exception) {
}
+5
source

you can use this:

String price="somevalue";
int priceInt=Integer.valueOf(price);

try{
if( !price.equals("") && priceInt>0){

// if condition is true,do your thing here!

}
}catch (NullPointerException e){

//if price is null this part will be executed,in your case leave it blank
}
catch (NumberFormatException exception) {
}
+2
source

All Articles