Redo the method statement

1

I would like to know how I can redo the instruction of a method until the user cancels.

I have the following method, for example:

public static void method(){
  int i = 1;
  i += 1;
  String choise;

  println("Exit?");
  choise = scan.next();

  if(choise.equals("y")){
    System.Exit(0);
  } else if(choise.equals("n")){
    /* ???? */
  } else{
    ...
  }
}

I imagine I could use a while loop, for example, and execute the statement until choise is "n". But I would like to know if it was possible to do this otherwise without using a loop.

    
asked by anonymous 29.09.2017 / 13:32

3 answers

7

We can solve the same problem with iterativa (using a loop of repetition) or through chamadas recursivas a uma função .

recursividade is the definition of a sub-rotina ( função or método ) that can invoke itself.

Knowing that we have more than one possibility of solution we should always look for the best for each situation #, in your case the ideal solution is through laço de repetição :

while (choise.equals("y")){

    println("Exit?");
    choise = scan.next();

    if(choise.equals("y")){
        System.Exit(0);
    } else if(choise.equals("n")){
        /* ... */
    } else {
        /* ... */
    }

}
    
29.09.2017 / 14:50
5

Try this:

while (choise.equals("y")){
    println("Exit?");
    choise = scan.next();

    if(choise.equals("y")){
        System.Exit(0);
    } else if(choise.equals("n")){
        /* ???? */
    } else{
        ...
    }
}

Or you can use another recursive method, which calls itself if it is not Y.

    
29.09.2017 / 13:43
-2

Do not use just reference

else if(choise.equals("n")){
      method();
    } else{
    
29.09.2017 / 13:58