谁能告诉我,为什么返回的值是3,而不是8不中return x从语句addFive方法改变的值x的main方法是什么?
public class App {
public static void main(String[] args) {
int x=3;
addFive(x);
System.out.println("x = " + x);
}
private static int addFive(int x) {
x += 5;
return x;
}
}
Run Code Online (Sandbox Code Playgroud)
您必须将返回值设置为变量,否则它会丢失并且您将在主方法中检索“x”的值。这样做是为了捕获返回值。
public static void main(String[] args) {
int x=3;
x = addFive(x);
System.out.println("x = " + x);
}
Run Code Online (Sandbox Code Playgroud)
如果您只想查看返回值而不存储它,您甚至可以将函数调用放在System.out.println.
public static void main(String[] args) {
int x=3;
System.out.println("x = " + addFive(x));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30990 次 |
| 最近记录: |