假设我有一个方法:
public static int square(int x) {
System.out.print(5);
return x*x;
}
我在main方法中调用这个方法如下:
System.out.print("The square of the number "+7+" is "+square(7));
我希望输出是
The square of the number 7 is 549
但是实际输出是
5The square of the number 7 is 49
为什么会这样?
最佳答案
当你调用一个函数时,所有的参数都会在函数被调用之前先被评估。
所以 "数字 "+7+"的平方是 "+square(7)
在打印它的 System.out.print
之前被求值。
因此 square(7)
被调用,然后调用 System.out.print(5)
first - 在调用 System.out.print
.
square(7)
返回 49 后,字符串的计算结果为 “数字 7 的平方是 49”
,然后打印出来。
为了让它更明确,就好像你这样做了:
String toPrint = "The square of the number "+7+" is "+square(7);
System.out.print(toPrint);
关于java - 以返回值的方式打印一些东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33584839/