【发布时间】:2016-11-10 23:03:16
【问题描述】:
我创建了一个将字符串值转换为新 Double 的方法。我想创建一个 if 语句来测试所述方法是否返回它应该执行的 null。这是到目前为止的代码:
内容类
public class Content
{
Double x;
String string = "b";
public void testParsing()
{
if (//call xMethod == null) {
System.out.println("Ovalid operator Success");}
else {
System.out.println("Invalid operator Fail");
}
}
/*
* Chops up input on ' ' then decides whether to add or multiply.
* If the string does not contain a valid format returns null.
*/
public Double x(String x)
{
String[] parsed;
if (x.contains("*"))
{
// * Is a special character in regex
parsed = x.split("\\*");
return Double.parseDouble(parsed[0]) * Double.parseDouble(parsed[1]);
}
else if (x.contains("+"))
{
// + is again a special character in regex
parsed = x.split("\\+");
return Double.parseDouble(parsed[0]) + Double.parseDouble(parsed[1]);
}
return null;
}
}
主类
public class MainClass {
public static void main(String[] args) {
Content call = new Content();
call.testParsing();
}
}
我知道以下行编译并输出为成功:(第 9 行)
if (x("") == null) {
但我不认为这是在做我要求它做的事情,我要求它检查 x 指向的方法的结果是否返回 null。任何有关如何正确调用此方法来检查该条件的说明将不胜感激,谢谢。
【问题讨论】:
-
@cricket_007:是什么让你这么认为?您认为违反了哪条 JLS 规则?
-
@JonSkeet 如何将字段与方法区分开来?
-
呸,found this。那是愚蠢的......
-
始终遵循命名约定并保持清晰。除了那个逻辑是正确的。 String string,Double x 和方法 x(String x) ...它是一些东西 :)
标签: java if-statement methods