println不会打印预期值

时间:2012-12-19 07:23:23

标签: java concatenation conditional-operator println

这是我的代码:

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 个答案:

答案 0 :(得分: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));

答案 1 :(得分:4)

尝试

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

答案 2 :(得分: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));

}

答案 3 :(得分: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));