用值返回方法打印东西

Tho*_*mas 5 java methods

假设我有一个方法:

public static int square(int x) {
    System.out.print(5);
    return x*x;
}
Run Code Online (Sandbox Code Playgroud)

我在main方法中调用此方法如下:

System.out.print("The square of the number "+7+" is "+square(7));
Run Code Online (Sandbox Code Playgroud)

我期待输出

The square of the number 7 is 549
Run Code Online (Sandbox Code Playgroud)

但是,实际输出是

5The square of the number 7 is 49
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

Cla*_*diu 10

调用函数时,在调用函数之前首先计算所有参数.

因此"The square of the number "+7+" is "+square(7)System.out.print打印它之前进行评估.

因此square(7)被调用,然后调用System.out.print(5) 第一 -调用之前System.out.print.

square(7)返回图49,字符串计算结果为"The square of the number 7 is 49",然后把它打印出来.

为了使它更加明确,就像你这样做:

String toPrint = "The square of the number "+7+" is "+square(7);
System.out.print(toPrint);
Run Code Online (Sandbox Code Playgroud)


Krz*_*soń -2

您有两个选择,要么返回要从方法打印的值,要么只在方法内执行 System.out.print。

您确实想5从打印吗square