I am writing a program that calculates Fibonacci numbers... But I keep getting an error on my code when I try to compile it...:

Fibonacci.java:18: illegal start of expression
public int calcFib (int n) {
^
1 error


I don't know what I am doing wrong? Someone help? Here's my code:

import java.util.Scanner;
public class Fibonacci {
    public static void main(String[] args) {
        int fib;
        int n;
        Scanner scan = new Scanner(System.in);
        System.out.println("input a number");
            n = scan.nextInt();
        
        public int calcFib (int n) {
        int ans;
        if (n<2) {
            ans = n;
            return ans;
            }
        else {
            ans = (n-1) + (n-2);
            return ans;
            }
        }
        System.out.println(calcFib(n));
    }
}
Member Avatar for iamthwee

public int calcFib (int n) {
^


Could it be the word public perhaps?

Member Avatar for Dukane

I think the problem here is that you are writing a method inside of a method.

The

public int calcFib(int n)

should not be contained in the main method. Instead, form the class like this:

public class Fibonacci {
[INDENT]public static void main(String[] args) {
[INDENT]//Insert main method body here
[/INDENT]}
public static int calcFib(int n) {
[INDENT]//Insert recursive method here
[/INDENT]}
[/INDENT]}

Notice how I changed the method declaration to include static. You'll need to do that since you're not instantiating an object from the Fibonacci class, you're calling it in the "static context" from your static main method.

After making those changes to your class, I was able to compile it and run it.

I tried your suggestion and it worked. I did not notice that it was outside the class. Thanks for the help!

Is this what you are looking for?

import java.util.Scanner;

public class Fibonacci {

	public static void main(String[] args) {

		int fib;

		int n;

		Scanner scan = new Scanner(System.in);

		System.out.println("input a number");

		n = scan.nextInt();

		System.out.println(calcFib(n));

	}
	public static int calcFib (int n) {

		int ans;

		if (n<2) {

			ans = n;

			return ans;

		}

		else {

			ans = (n-1) + (n-2);

			return ans;

		}

	}

}
commented: You just 4 years too late with your answer that is poorly coded -3
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.