java - 以返回值的方式打印一些东西

标签 java methods

假设我有一个方法:

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/

相关文章:

java - 为什么Java中函数修改数组[0]而不修改字符串?

java - 添加新的 ListView 项目并从另一个 Activity 获取项目的值

java - ClassLoader类依赖(插件)

java - 如何重新提示允许用户继续转换值?

java - 我在 Java 方法上遇到困难

java - 如何从方法内部更改变量的值?

java - Maven:如何从命令行传递参数运行 .java 文件

java java.lang.reflect.Array.getLength 与 array.length

java - 支付网关集成时获取 SSLException

ios - 方向改变后放置方法的理想位置