简体   繁体   中英

How to execute a statement within a recursive method only once in Java?

I need to execute a statement within a recursive method only once in Java, without using any of the variables in the method parameters, without any external variables outside the method, and the statement must be inside the method.

public static boolean recursiveMethod(int x) {
    if (x >= 5) {
        return true;
    }
    boolean isPrintedOnce = false;
    if (isPrintedOnce == false) {
        System.out.println("Printed once!"); // Print this statement only once
        isPrintedOnce = true;
    }
    return recursiveMethod(x + 1);
}

public static void main(String[] args) {
    System.out.println(recursiveMethod(0));
}

This doesn't work because "boolean isPrintedOnce = false;" is executed five times so the conditional statement is useless. I get this as my output:

Printed once!
Printed once!
Printed once!
Printed once!
Printed once!
true

EDIT: The requirements are that, 1) can't use external variables outside of the method 2) no use of variables in method parameters 3) the statement must be inside the method (My assignment requires this. I might have read it wrong because it seems impossible with these requirements but I believe these are requirements in it.)

How about wrapping it in a helper method?

public static boolean recursiveMethodHelper(int x) {
    System.out.println("Printed once!");
    return recursiveMethod(x)
}

public static boolean recursiveMethod(int x) {
    if (x >= 5) {
        return true;
    }
    return recursiveMethod(x + 1);
}

public static void main(String[] args) {
    System.out.println(recursiveMethodHelper(0));
}

Note that this has the side effect of always printing, even if x>=5 from the start. However, no variables are declared outside, and no parameters are added, as per your requirements.

Put the System.out.println("Printed once!"); in the if (x >= 5) condition since the base case should only ever be true once in a recursive call.

You can use this trick to get the depth of the stack from an Exception object, and only print at a certain depth:

  public static boolean recursiveMethod(int x) {
    if (x >= 5) {
      return true;
    }
    Exception e = new Exception();
    e.fillInStackTrace();
    if (e.getStackTrace().length == 2) {
      System.out.println("Printed once!"); // Print this statement only once
    }
    return recursiveMethod(x + 1);
  }

  public static void main(String[] args) {
    System.out.println(recursiveMethod(0));
  }

Solution with the 2nd parameter will execute special code once per each external method call.

public static boolean recursiveMethod(int x, boolean isFirstCall) {
    if (x >= 5) {
        return true;
    }

    if (isFirstCall) {
        System.out.println("Printed once!"); // Print this statement only once

    }
    return recursiveMethod(x + 1, false);
}

public static void main(String[] args) {
    System.out.println(recursiveMethod(0, true));
}

You can hide this 2nd parameter by overloading the method and making 2-parameter version private .

public static boolean recursiveMethod(int x) {
    recursiveMethod(int x, true);
}

private static boolean recursiveMethod(int x, boolean isFirstCall) {
    if (x >= 5) {
        return true;
    }

    if (isFirstCall) {
        System.out.println("Printed once!"); // Print this statement only once

    }
    return recursiveMethod(x + 1, false);
}

public static void main(String[] args) {
    System.out.println(recursiveMethod(0);
}

You could use what is called a helper method. The idea is that you make your recursive method private (doens't actually need to be private) and accept everything it needs as parameters. You then create a second method that is used used by the developer and sets up the recursive method by passing in a specific set of parameters.

Lets see an example:

// This method is the one that our developer can use
public static boolean recursiveMethod(int x) {
    recursiveMethod(x, true); // Any time the recursive method is called from here, we know it's the first time!
}

// This is our real one, hidden from view and accessed only by our controlled helper
private static boolean recursiveMethod(int x, boolean firstTime) {
    if (x <= 5) {
        return true;
    }

    if (firstTime) {
        System.out.println("It's the first time!");
    }

    return recursiveMethod(x+1, false); // Anytime this method is called recursively here, we know it isn't the first time!
}  

The nice thing about this helper approach is that you don't need to globalize anything, while still hiding unnecessary attributes from the person using it. From the his/her point of view, it looks exactly the same.

Try this code

public static boolean recursiveMethod(int x) {
if (x >= 5) {
    return true;
}
boolean isPrintedOnce = false;
if (isPrintedOnce = false) {
    if(x==0){
    System.out.println("Printed once!"); // Print this statement only once
    }
    isPrintedOnce = true;
}
return recursiveMethod(x + 1);
}

public static void main(String[] args) {
System.out.println(recursiveMethod(0));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM