简体   繁体   中英

how to call non-static methods in main method

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));
    }
}

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);

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.

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