Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

Recursion with JAVA

  Asked By: Pamela    Date: Feb 11    Category: Java    Views: 5228
  

I have a question,
When we do recursion JAVA creats a stck in the systems and
automatically stores all recursive methods records in that stack, My
question: Is there any way that we can access or read the
information in that stack?

Share: 

 

2 Answers Found

 
Answer #1    Answered By: Adaulfo Fischer     Answered On: Feb 11

that would be dangerous. write your own method to control that.

 
Answer #2    Answered By: Nicholas Wells     Answered On: Feb 11

I usually generate an Exception. This piece of code (the catch
block) very similar to a piece of code used by me at work. I hope
you find it usefull:


// Method that calls itself several times to test the Stack
void stackTraceExample(int i) {
try {
if(i<10) // If I have not executed enoght times
stackTraceExample(i+1) // I execute one more time
else
throw new Exception(); // I generate an exception
} catch(Exception ex) {
String string_error = "";
StackTraceElement stackTraceElements[] = ex.getStackTrace();

int maxLenMetodo = -1;
int maxLenClase = -1;
for(int i=0;i<stackTraceElements.length;i++) {
StackTraceElement stackTraceElement = stackTraceElements[i];
if(stackTraceElement.getMethodName().length()
>maxLenMetodo) maxLenMetodo = stackTraceElement.getMethodName
().length();
if(stackTraceElement.getClassName().length()
>maxLenClase) maxLenClase = stackTraceElement.getClassName
().length();
}

for(int i=0;i<stackTraceElements.length;i++) {
StackTraceElement ste = stackTraceElements[i];
string_error = string_error+"Class="+ste.getClassName()
+espacios(maxLenClase, ste.getClassName())+
" Método="+ste.getMethodName()
+espacios(maxLenMetodo, ste.getMethodName())+
" Archivo="+ste.getFileName()
+":"+ste.getLineNumber()+
"\n";
}
System.err.println(string_error);
}
}

 
Didn't find what you were looking for? Find more on Recursion with JAVA Or get search suggestion and latest updates.




Tagged: