package cn.vanke.stackTrace;
import java.util.Scanner;
public class StackTraceTest {
public static int factorial(int n)
{
System.out.println("factorial("+n+"):");
Throwable t = new Throwable();
StackTraceElement[] frames = t.getStackTrace();
for(StackTraceElement f : frames)
{
System.out.println(f);
}
int r;
if (n<= 1)
{
r = 1;
}
else
{
r = n * factorial(n-1);
}
System.out.println("return " + r);
return r;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter n:");
int n = in.nextInt();
factorial(n);
}
}
我不懂得控制台的结果,那个行数是代表什么,到底是怎么样的一行才会被trace?
factorial(3):
cn.vanke.stackTrace.StackTraceTest.factorial(StackTraceTest.java:9)//为什么直接到9?
cn.vanke.stackTrace.StackTraceTest.main(StackTraceTest.java:33) //为什么又回到33?
factorial(2):
cn.vanke.stackTrace.StackTraceTest.factorial(StackTraceTest.java:9)
cn.vanke.stackTrace.StackTraceTest.factorial(StackTraceTest.java:22)
cn.vanke.stackTrace.StackTraceTest.main(StackTraceTest.java:33)
factorial(1):
cn.vanke.stackTrace.StackTraceTest.factorial(StackTraceTest.java:9)
cn.vanke.stackTrace.StackTraceTest.factorial(StackTraceTest.java:22) //为什么这边两个22行?
cn.vanke.stackTrace.StackTraceTest.factorial(StackTraceTest.java:22)
cn.vanke.stackTrace.StackTraceTest.main(StackTraceTest.java:33)
return 1
return 2
return 6
------解决思路----------------------
理解函数调用栈就明白了