I basically have the entire program done except for one little problem my maxDepth output is wrong!

But the rest of the assignment is after your program gets the correct answers, add static variables calls, depth, and maxDepth to your class and add code to your implementation of Z to keep track of total number of calls to the Z method and the maximum depth of the activation stack. To do the latter you must increment depth, whenever you enter Z and decrement it when you leave. maxDepth is the largest value that depth achieves during your run. Your main should display calls and maxDepth when it displays the value computed for the Z function.

Ok now that you know what I'm trying to do here is my input and what the answers are suppose to be input is 2 for x, 3 for y

Outs puts are suppose to be z value is 9, calls = 44 and maxDepth = 10

I get all of those except maxDepth = 22 not 10

``````import javax.swing.*;

public class ZFunction {
public static int calls = 0;
public static int depth = 0;
public static int z1;
public static int z2;
public static int maxDepth = 0;

public static int z(int x, int y){
calls++;
depth++;

if (x==0){
if (depth > maxDepth)
maxDepth = depth;
return y+1;}
else if (x>0 && y==0){
z1 = z(x-1,1);
depth = depth -1;
return z1;}

else{
z2 = z(x-1,z(x,y-1));
depth = depth -1;
return z2;
}

}

public static void main(String[] args) {
String a = JOptionPane.showInputDialog("Enter the x value");
int x = Integer.parseInt(a);

String b = JOptionPane.showInputDialog("Enter the y value");
int y = Integer.parseInt(b);

JOptionPane.showMessageDialog(null, "The value of z is" + z(x,y));
JOptionPane.showMessageDialog(null, "Z method was called" + calls);
JOptionPane.showMessageDialog(null, "Z method was max depth" + maxDepth);
}
}``````
2
Contributors
2
Replies
3
Views
9 Years
Discussion Span
Last Post by Noliving

As the post is marked as solved I guess you found the problem. Would you mind to share your solution?

Ya it was a one line solution, after line 21 you have to add:

depth = depth -1;

So lines 14 too 36 or more like 37 from the orignal/first post shoud look like this:

``````public static int z(int x, int y){
calls++;
depth++;

if (x==0){
if (depth > maxDepth)
maxDepth = depth;
depth = depth -1;
return y+1;}
else if (x>0 && y==0){
z1 = z(x-1,1);
depth = depth -1;
return z1;}

else{
z2 = z(x-1,z(x,y-1));
depth = depth -1;
return z2;
}

}``````