-3

im trying to make a program where the user enters a number and the console is that fibonacci number. im having trouble figuring out why the like fibbonaci fib = new fibonacci is stopping my program. when the computor reads that line, the code juts stops to run.

Edit: Thanks so much for the answers guys, but im still having trouble understanding. could somone please rewrite the code so that the error is fixed? thanks!

Edit: i figured it out, thanks for all the help!

import java.util.Scanner;

public class fibonacci {
    Scanner fnumber = new Scanner (System.in);
    int input = fnumber.nextInt();
    int f1 = 1;
    int f2 = 1;
    int answer = f1 + f2;

    public int fibonacci( int input) {
        for(int f2 = 1; f2<input; f2++ ) {
            int answer = f1 + f2;
            f1 = f2;
            f2 = f2 + 1;
        }
        return answer;
    }

    public static void main(String args[]){
        System.out.println("please enter a number");
        Scanner fnumber = new Scanner (System.in);
        int input = fnumber.nextInt();
        System.out.println("The " + input + "th number of the fibonacci sequence is " + fib.fibonacci(input));
    }
}
  • Your method `public int fibonacci(int input)` should be named something else. The only method that should have the same name as your class is the constructor. Also your variables `f1`, `f2`, and `answer` should be declared inside of your method, there's no reason for them to be instance variables. And remove the declaration of `input` and `fnumber` from the top of your fibonacci class, they're not used. – Flaom Oct 12 '17 at 01:23
  • I'd have a look at some other things as well. When you say `int answer` _in_ the `for` loop, this is a new variable (not the field on your class). When you `return answer` _outside_ the `for` loop, you're returning the field (with the same name) which has not been modified within the loop. Same with the `int f2 = 1;` declaration in the `for` loop's opening. – BeUndead Oct 12 '17 at 01:23
  • And inside of your for loop, you are initializing another `answer` variable, which is never used after being initialized. Remove the `int` type specifier from `answer` inside of the for loop. – Flaom Oct 12 '17 at 01:24

2 Answers2

0

You have to create an object of your class. then call the method using object in main method (static).

fibonacci fib = new fibonacci();
fib.fibonacci(input);
0

instantiate the fibonacci class in your main.

fibonacci f = new fibonacci ();
f.fibonacci(input);

Also, your class (and file) should be named Fibonacci. Classes name always have a capital first letter.

Bruno Delor
  • 308
  • 2
  • 10