Java System.out.println()帮助。操作员麻烦?

时间:2014-10-14 07:14:45

标签: java console output

有人可以告诉我他们认为什么是输出?说实话,我不明白为什么我错了。

int a = 9; 
int b = 3; 
int c = 4; 

System.out.println((a+b) + c + " = " + a + b + c); 
System.out.println(a + b + c + " = " + a + (b + c)); 

我认为输出将是124 = 934和934 = 97。 Jcreator说这是16 = 934和16 = 97.有人可以解释一下吗?

2 个答案:

答案 0 :(得分:1)

让我们看看:

  System.out.println((a+b) + c + " = " + a + b + c); 

我们应该从从左到右执行

  (a + b) + c - the result is int so far and it's 16

但是,当我们添加" = "时,结果将变为String,而一个String,因为:

  (a+b) + c + " = " // String equals to "16 == "

现在我们正在添加String

  (a+b) + c + " = " + a         is "16 = 9"  (note a is treated as a String)
  (a+b) + c + " = " + a + b     is "16 = 93" (note a, b are treated as String)
  (a+b) + c + " = " + a + b + c is "16 = 934" (note a, b, c are treated as String)

  System.out.println(a + b + c + " = " + a + (b + c)); 

我们首先执行 (b + c)int 7 a + b + c is int == 16 a + b + c + " = " becomes String == "16 = " a + b + c + " = " + a is String == "16 = 9" a + b + c + " = " + a + (b + c) is String == "16 = 97" // (b+c) was computed before 然后从左到右继续 < / p>

{{1}}

答案 1 :(得分:0)

按照您构建它的方式,您可能无法获得所需的结果。

执行从左到右主要发生。

请参阅下面的修改版本..注意在几个地方添加一个空字符串,以阻止数字计算发生并改为字符串连接。

System.out.println((a+b) + "" + c + " = " + a + b + c); 
System.out.println(a + "" + b + "" + c + " = " + a + (b + c));