java 比较两个字符串的“大于 '0' ..and NULL”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10573788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 01:37:39  来源:igfitidea点击:

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

javastring-comparisoncomparison-operators

提问by richey

I am trying to dig my way through the strict Java methods and operators, but now, trying to 'translate' a piece of PHP code to Java (Android), I'm kinda stuck.

我试图通过严格的 Java 方法和运算符挖掘自己的方法,但是现在,试图将一段 PHP 代码“翻译”为 Java (Android),我有点卡住了。

In PHP:

在 PHP 中:

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

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

问题是 $row['price'] 可能为空(在 Java 中:null?)或包含 '0'(零)。但是我怎样才能以一种聪明而不是太复杂的方式在 Java 中编码呢?

回答by smichak

Assuming you got the price string in a variable price

假设您以可变价格获得价格字符串

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

回答by JahN EstaCado

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) {
}