奇怪的java打印输出
我是 Java 新手,正在处理简单的打印。首先,我执行:
System.out.println(1 + 2 + "3");
输出:33
我编写了将 1 和 2 添加到一起并按原样打印 3 的逻辑。
然后,我尝试了这个:
System.out.println ("1" + 2 + 3);
输出:123
应用该逻辑我得到了答案 15 ,无法计算出正确的答案,所以我需要你的帮助,所以朋友们。
I am new to Java and was working with simple printing. First, I executed:
System.out.println(1 + 2 + "3");
Output:33
I made up logic that 1 and 2 will be added and 3 will be printed as is.
Then, I tried this:
System.out.println ("1" + 2 + 3);
Output:123
Applying that logic I got answer 15 ,couldn't work-out the correct answer, so I need your help, SO friends.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
运算符
+
从左侧计算,因此您的第二个示例将这样解释:如果您想显示
15
那么您应该执行以下操作:这样
(2 +3)
将首先被评估。Operator
+
is evaluated from the left so your second example is interpreted this way:If you want to display
15
then you should do the following:This way
(2+3)
will be evaluated first.表达式
1 + 2
是一个int
。然后将
"3"
连接到该 int。表达式
“1”+ 2
是一个字符串
。然后,您将
3
连接到该String
。您正在考虑
"1" + (2 + 3)
,但这不会发生,因为 Java 是左关联的。The expression
1 + 2
is anint
.You're then concatenating
"3"
to that int.The expression
"1" + 2
is aString
.You're then concatenating
3
to thatString
.You're thinking of
"1" + (2 + 3)
, which doesn't happen because Java is left-associative.在第一种情况下,Java 将数字相加得到结果 3,并且附加字符串 3 使其成为连接字符串:“33”。
在第二种情况下,结果是一个字符串,因为“1”和其他字符串连接起来成为“123”
In the first case Java adds the numbers to get the result 3 and the appending of the string 3 causes it to become the concatenated string: "33".
In the second case the result is a string because of the "1" and the others get concatenated to become "123"