简体   繁体   English

如何在main方法中调用非静态方法

[英]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.我无法弄清楚为什么像 fibbonaci fib = new fibonacci 会停止我的程序。 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.在你的 main.js 中实例化 fibonacci 类。

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

Also, your class (and file) should be named Fibonacci.此外,您的类(和文件)应命名为 Fibonacci。 Classes name always have a capital first letter.类名的首字母总是大写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM