我有一个关于带整数和字符串的java算术的问题。例如,
int a = 1;
int b = 3;
int c = 5;
System.out.println(a + b + (c + " = ") + a + (b + c));
System.out.println((a + b) + c + " = " + a + b + c);
System.out.println(a + (b + c) + " = " + (a + b) + c);
以上代码分别输出"45 = 18“、"9 = 135”和"9 = 45“。我不明白这次行动背后的逻辑。我的第一反应是他们都输出了"9 = 9“。我希望有人能帮我理解这次行动。我很感激你的帮助!
发布于 2019-03-20 04:54:33
加法是左关联的,但括号可以改变执行顺序。
因此,如果我们必须在这里分解第一个println
,当我们编写a+b
时,它会导致算术加法(5)
,但是当我们执行c + " = " + a + b + c
时,它会导致字符串级联5=9
,因为c + " = "
首先计算并将表达式作为String + int
操作,从而导致字符串连接。记住,int+int
是int
,String+int
是String
由于括号()
,表达式的计算方式发生了变化。如果我们包含括号,上面的表达式就是这样计算的。
(c + " = ") + a + (b + c)
- First it evaluates (c + " = "), so the expression becomes 5 = + a + (b + c)
- Now it evaluates b+c because of parenthesis, , so the expression becomes 5 = + a + 8
- Now as there are not parenthesis, it evaluates the expression from left to
right and as the first operand is string, the whole expression becomes a
string concatenation operation
第一表达式的完全分解
a + b + (c + " = ") + a + (b + c)
- First precedence is of (b + c), so now it becomes a + b + (c + " = ") + a+8
- Next precedence is of (c + " = "), so now it becomes a + b + "5 = " + a+8
- Now as there is not (), expression is evaluated from left to right, so
now it evaluates a + b , so it becomes 4 + "5 = " + a+8
- now it evaluates '4 + "5 = "', so it becomes `45 = a + 8`, because we have
now a string in the expression, so it does string concatenation
- and it becomes `45 = 18`
类似地,您可以分解另外两个表达式。
发布于 2019-03-20 04:56:03
这里的要点是,您正在将int加法+与字符串连接+操作混合在一起。
在计算1+3时,生成4,然后将其放在"5 = 1“字符串前面,然后是5+3 (8)的结果。
不同的结果是基于不同的效果放置支撑。
发布于 2019-03-20 05:04:06
如果您将int与字符串连接在一起,那么它将导致字符串,并通过添加括号来更改您的示例的执行结构: System.out.println(a +b+ (c + ") +a+ (b + c));
(b + c)
将解析为8(c + " = ")
将被解析为"5=“a + b
将导致4a + b + (c + " = ")
此语句将成为字符串值4+"5=“,输出将为"45=”。a + b + (c + " = ")
+a连接,生成"45=“+1,并生成"45=1”。a + b + (c + " = ") + a + (b + c)
解析为"45=1“+8,因此最终结果是"45=18”。https://stackoverflow.com/questions/55253752
复制相似问题