三元打印操作
printing operation with the ternary
我经常使用以下 if
块(没有 else/elseif 子句;仅用于特定检查)
if(value==10){system.out.print("true");}
所以我尝试将它与三元一起使用:
(a==1)?System.out.println("true");
但它不起作用。主要是,我想知道三元运算符是否可以像单个 if 一样工作? (虽然我没有考虑过,但它能像 if-else_if-else 子句那样工作吗?)
您想要实现的目标是不可能的。但是,如果你必须使用三元,试试这个
String a = (value==10) ? "Yes" : "No";
System.out.println(a);
否则你也可以这样做,
System.out.println((value==10)?"Yes":"No");
首先,正如 Kevin 所提到的,三元运算符应该有一个左手赋值变量。
其次,它应该始终伴随着 else 操作
以下表达式有效。
<code>String s = a==10 ? "true" : "false";
System.out.println(s);
三元运算符只是 shorthand 对应 if-else,但它必须 return 某种东西。您需要使用格式
something = (x)?(if x==true, return this):(if x==false, return this)
做你想做的,在打印语句中放一个三元组。即
System.out.println((a==1)?("true"):(""));
除了上述答案之外,如果要将字符串聚合到表达式中,您可以使用以下代码片段:
System.out.println("any text you want"+ (value == 10)?"value is greater than 10":"value is lower than 10");
我经常使用以下 if
块(没有 else/elseif 子句;仅用于特定检查)
if(value==10){system.out.print("true");}
所以我尝试将它与三元一起使用:
(a==1)?System.out.println("true");
但它不起作用。主要是,我想知道三元运算符是否可以像单个 if 一样工作? (虽然我没有考虑过,但它能像 if-else_if-else 子句那样工作吗?)
您想要实现的目标是不可能的。但是,如果你必须使用三元,试试这个
String a = (value==10) ? "Yes" : "No";
System.out.println(a);
否则你也可以这样做,
System.out.println((value==10)?"Yes":"No");
首先,正如 Kevin 所提到的,三元运算符应该有一个左手赋值变量。
其次,它应该始终伴随着 else 操作
以下表达式有效。
<code>String s = a==10 ? "true" : "false";
System.out.println(s);
三元运算符只是 shorthand 对应 if-else,但它必须 return 某种东西。您需要使用格式
something = (x)?(if x==true, return this):(if x==false, return this)
做你想做的,在打印语句中放一个三元组。即
System.out.println((a==1)?("true"):(""));
除了上述答案之外,如果要将字符串聚合到表达式中,您可以使用以下代码片段:
System.out.println("any text you want"+ (value == 10)?"value is greater than 10":"value is lower than 10");