繁体   English   中英

为什么在使用布尔语句时,内容不打印在 system.out.println 语句中

[英]Why the content is not printing inside the system.out.println statement while using a boolean statement

数据未显示在 system.out.println 语句中

带括号它正在工作并且等于方法

final String s1="all men are created equal:27";
final String s2="all men are created equal:"+s1.length();
System.out.println("all men are created equal:" + (s1==s2));

输出:人人生而平等:假

final String s1="all men are created equal:27";
final String s2="all men are created equal:"+s1.length();
System.out.println("all men are created equal:" + (s1.equalsIgnoreCase(s2)));
System.out.println();

输出:人人生而平等:假

final String s1="all men are created equal:27";
final String s2="all men are created equal:"+s1.length();
System.out.println("all men are created equal:" + s1==s2);
System.out.println();

输出:假

为什么“人人生而平等:”不是印刷

您使用的运算符具有不同的优先级 ==运算符的优先级低于+运算符(就像数学中+的优先级低于* ),因此您的表达式

"all men are created equal:" + s1==s2

以这种方式解析:

("all men are created equal:" + s1) == s2

它正在比较"all men are created equal:" + s1是否等于s2 这个表达式的结果是一个boolean 因此,只打印false

通过添加括号,您明确表示您希望首先评估s1==s2部分,然后是+运算符。 这就像1+2*3(1+2)*3

另请注意,您应该将字符串与equals进行比较,而不是==

"all men are created equal:" + s1.equals(s2)

. 运算符具有非常高的优先级,高于+ ,因此在这种情况下您不需要括号。

由于 java 中的运算符优先级,最后一个打印仅显示 false。 首先,它将“人人生而平等:”与字符串 s1 连接起来。 然后比较连接的字符串是否等于 s2 并打印输出。 如您所见,连接的字符串不等于 s2。

仅仅因为"all men are created equal:" + s1"all men are created equal:" + s1s2不相等。

使用上面的表达式,您正在检查"all men are created equal:" + s1"all men are created equal:" + s1s2是否相等。 由于"all men are created equal:" + s1"all men are created equal:" + s1s2不相等,因此结果将为false

如果你想获得预期的行为,你应该在s1==s2周围使用括号。

"all men are created equal:" + (s1==s2)

将“()”添加到 s1==s2。 像这样:

System.out.println("all men are created equal:" + (s1==s2));

原因如下:

"all men are created equal:" + s1 => "all men are created equal:false"
"all men are created equal:false" == s2 => false
PRINT false

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM