user1477348
user1477348

Reputation: 33

Why wont this code run?

Ultra java noob here, I am sure its probably a silly mistake. Some care to correct me?

public class Test1 {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // TODO code application logic here
int n = 4;

public void f(int n){
 System.out.print(n);
 if(n<=1)
  return;
  else{
      f(n/2);
      f(n/2);
      }
   }
 }

I'm getting this error:

Exception in thread "main" java.lang.RuntimeException:
Uncompilable source code - illegal start of expression at the
public void f(int n)

Upvotes: 0

Views: 756

Answers (4)

Pshemo
Pshemo

Reputation: 124235

Because for compiler your code looks like this

public class Test1 {

    public static void main(String[] args) {
        int n = 4;


        public void f(int n) {
            System.out.print(n);
            if (n <= 1)
                return;
            else {
                f(n / 2);
                f(n / 2);
            }
        }
    }

so it has 2 errors

1) you are trying to create method in method (f inside main)

2) no } at the end of class

Upvotes: 0

Francisco Spaeth
Francisco Spaeth

Reputation: 23903

The structure needs to be a bit different, try this approach:

public class Test {

    public static void main(final String[] args) {
        f(4);
    }

    public static void f(final int n) {
        System.out.print(n);
        if (n <= 1) {
            return;
        } else {
            f(n / 2);
            f(n / 2);
        }
    }
}

Upvotes: 3

Leniel Maccaferri
Leniel Maccaferri

Reputation: 102418

Do this:

public static void main(String[] args)
{
    // TODO code application logic here
    int n = 4;

    f(n);  
}

public void f(int n)
{
    System.out.print(n);

    if( n <= 1)
    {
      return;
    }
    else
    {
        f(n/2);
    }
}

Upvotes: 1

Joey
Joey

Reputation: 354576

You cannot declare methods within methods in Java. You're missing a } somewhere before public void f(int n).

Upvotes: 3

Related Questions