简体   繁体   中英

Calling method within itself

I wanted to make an input which accepts numbers from 1 - 10 and prints the range.

I need to check if the input is an integer (check), check if the range is 0-10 (check), and if it's not any of those things, to ask the user again. So, a recursive method?

Currently I have this:

import java.util.Scanner; 
import java.util.InputMismatchException; 

public class FinalTest {
  public static void main (String [] args) {

    Scanner in = new Scanner(System.in);
    int k = 0;

    System.out.print("int - ");

    try {
      k = in.nextInt();
    } catch (InputMismatchException e) {
      System.out.println("ERR: Input");
      System.exit(1);
    }

    if(k <= 10 && k > 0) {
      for(int j=1; j <= k; j++) {
        System.out.println(j);
      }
    } else {
      System.out.println("ERR: Oob");
      System.exit(1);
    }
  }
}

I would like to replace the "System.exit()" so that it re attempts to ask the user for input again.

calling main(); produces an error.

How do I correctly call the main method in this case?

Two choices here:

  • actually create a method and call that
  • simply use a loop

Loop could go like:

boolean askForInput = true;
while ( askForInput ) {
  try {
    k = in.nextInt();
    askForInput = false;
  } catch ...
    print "not a number try again"
}

But beyond that: you still want to put this code into its own method. Not because that code should call itself, but for clarity reasons. Like:

public static int askForNumber(Scanner in) {
  ... code from above
  return k;
}

And to answer your question: you do not want to use recursion here. You want to loop ; and yes, recursion is one way to implement looping, but that is simply overkill given the requirement you want to implement here.

And for the record: when creating that helper method, you can actually simplify it to:

public static int askForNumber() {
  while ( askForInput ) {
    try ...
      return in.nextInt();
    } catch ...
    print "not a number try again"
  }
}

Beyond that: you typically use recursion for computational tasks, such as computing a factorial, or fibonacci number, ... see here for example.

for the part of the recursive method printing a range:

public void printAscending(int n) {
  if (n > 0) {
     printAscending(n - 1);
     System.out.println(n);
  }
}

I think using recursion is just too much for something that simple and would probably be more expensive. You can add a while loop around your scanning bit until the entered value is valid. I would also put the printing loop out of the while to not have to test a condition before printing since if you get out of the while loop, it means number if valid. You could test just the -1 value to exit process.

public class FinalTest
{
    public static void main (String [] args)
    {
        Scanner in = new Scanner(System.in);
        int k = 0;

        do
        {
            System.out.print("int - ");

            try
            {
                k = in.nextInt();
            }
            catch (InputMismatchException e)
            {
                System.out.println("ERR: Input");
                System.exit(1);
            }
        }
        while(!(k>0 && k<=10) && k!=-1);

        if(k!=-1)
        {
            for(int j=1; j<=k; j++)
            {
                System.out.println(j);
            }
        }
        else
        {
            System.out.println("Bye Bye.");
        }
    }
}

Okay, so what I personally do when I need to use recursion is I create a separate function/method for it. And when I need to restart the method, I just call it within itself. So it would be something like this:

private void recursiveMethod() {
// do stuff . . .
if (yourCondition) {
    //continue to next piece of code
} else {
    recursiveMethod();
}

}

But in big projects, try to stay away from recursion because if you mess up, it can

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