【发布时间】:2021-03-01 11:45:54
【问题描述】:
谁能解释这段代码中发生了什么。代码仅在传递 -1 时终止。在此之前,它一直要求用户输入。并且只有在终止后,它才会从输入值中打印 3 的倍数。我很困惑 x 的所有值在终止之前存储在哪里。
public class Recursion {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
multipleThree(in);
}//end of main
public static void multipleThree(Scanner in) {
System.out.println("Enter the list(-1 to terminate):");
int x = in.nextInt();
if (x == -1) {
return;
} else {
multipleThree(in);
if (x % 3 == 0)
System.out.println(x + " is divisible by 3");
}//end of else
}//end of method
}//end of class
【问题讨论】:
-
每次调用方法时,都会为其变量和参数保留一些内存(通常称为帧)-因此每次调用都有自己的变量版本-因为
int x在内部声明了一个变量该方法,它被保存在那个内存(帧)中。不仅与递归调用有关,而且与递归方法的工作有关。 [由于调用multipleThree后输出,所以只会在调用返回后执行]
标签: java algorithm recursion methods