7

这是我的代码:

public static void main(String[] arg)
{

    String x = null;
    String y = "10";
    String z = "20";

    System.out.println("This my first out put "+x==null?y:z);

    x = "15";

    System.out.println("This my second out put "+x==null?y:z);

}

我的输出是:

20
20

但我期待这个:

This my first out put 10
This my second out put 20

有人可以解释一下为什么两个 println 调用的输出都为“20”吗?

4

4 回答 4

9

System.out.println("This my first out put "+x==null?y:z); 将像执行

("This my first out put "+x)==null?y:z这永远不会是真的。因此,它将显示z价值。

例如:

int x=10;
int y=20;
System.out.println(" "+x+y); //display 1020
System.out.println(x+y+" "); //display 30

对于上述情况,操作从左到右执行。

正如你所说,你期待这个:

This my first output 10

为此,您几乎不需要更改代码。尝试这个

System.out.println("This my first output " + ((x == null) ? y : z));

于 2012-12-19T07:25:31.300 回答
4

尝试

System.out.println("This my first out put "+ (x==null?y:z));
于 2012-12-19T07:25:03.963 回答
2

使用以下代码将解决您的问题:问题是因为它采取 -

System.out.println(("This my first out put "+x==null?y:z);   

作为

System.out.println(("This my first out put "+x)==null?y:z);

public static void main(String[] arg)
{

    String x = null;
    String y = "10";
    String z = "20";

    System.out.println("This my first out put "+(x==null?y:z));

    x = "15";

    System.out.println("This my second out put "+(x==null?y:z));

}
于 2012-12-19T07:29:12.297 回答
1

你需要尝试:

System.out.println("This my first out put "+(x==null?y:z));
x = "15";
System.out.println("This my second out put "+(x==null?y:z));
于 2012-12-19T07:26:56.530 回答