Methods inside methods

java, methods

Solution

No, not directly; however, it is possible for a method to contain a local inner class, and of course that inner class can contain methods. This StackOverflow question gives some examples of that.

In your case, however, you probably just want to call `countdown` from inside `main`; you don't actually need its entire definition to be inside `main`. For example:

class Blastoff {

    public static void main(String[] args) {
        countdown(Integer.parseInt(args[0]));
    }

    private static void countdown(int n) {
        if (n == 0) {
            System.out.println("Blastoff!");
        } else {
            System.out.println(n);
            countdown(n - 1);
        }
    }
}

(Note that I've declared `countdown` as `private`, so that it can only be called from within the `Blastoff` class, which I'm assuming was your intent?)

Problem

Is it syntactically correct to have a method inside the main method in Java? For example ``` class Blastoff { public static void main(String[] args) { //countdown method inside main public static void countdown(int n) { if (n == 0) { System.out.println("Blastoff!"); } else { System.out.println(n); countdown(n - 1); } } } } ```

Original source

Related problems