Java算术:为什么它们不是“ 9 = 9”?

时间:2019-03-20 04:48:15

标签: java

我对整数和字符串的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”。我希望有人可以帮助我了解此操作。感谢您的帮助!

4 个答案:

答案 0 :(得分:1)

加法是左关联的,但是括号可以更改执行顺序。

因此,如果我们必须在此处分解第一个println,则在编写a+b时会导致算术加法(5),但是在执行c + " = " + a + b + c时会导致字符串串联5=9,因为c + " = "首先求值,并将表达式作为String + int运算,导致字符串串联。请记住,int+intint,而String+intString

由于括号(),表达式的计算方式发生了变化。如果我们加上括号,这就是上面表达式的计算方式

(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`

类似地,您可以分解其他两个表达式

答案 1 :(得分:1)

这里的要点是您正在将int加法+与字符串串联+操作混合在一起。

在您的计算中,得出1 + 3,结果为4。然后将其放在字符串“ 5 = 1”前面,然后是5 + 3(8)。

然后基于放置括号的不同效果得出不同的结果。

答案 2 :(得分:0)

如果用字符串conint int则将产生字符串,并通过添加方括号来更改执行结构 你的例子: System.out.println(a + b +(c +“ =”)+ a +(b + c));

  1. 3 将解析为8
  2. (b + c)将解析为“ 5 =“
  3. 语句开始处的
  4. (c + " = ")将得到4
  5. a + b该语句将成为字符串值4+“ 5 =”,输出将是“ 45 =”
  6. 然后将其与a + b + (c + " = ") + a串联,结果为“ 45 =” + 1,结果为“ 45 = 1”
  7. 因此整个语句将变为a + b + (c + " = ")解析为“ 45 = 1” + 8,因此最终结果为“ 45 = 18”

答案 3 :(得分:0)

+操作有两个含义。第一个含义是多个数值之间的算术加法运算。例如

System.out.println(1 + 2 + 5);  

以上打印结果为9。
第二个含义是String与其他字符串之间的String串联。例如

System.out.println(9 + "=" + 9);  

以上打印结果为“ 9 = 9”。
我认为您可能希望打印加法的交换定律。以下可能是您想要的。

int a = 1, b = 3, c = 5;
System.out.println( (( a + b ) + c ) + "=" + ( a + ( b + c )) );