【问题标题】:non static method cannot be referenced from a static context, can't call the method below不能从静态上下文中引用非静态方法,不能调用下面的方法
【发布时间】:2017-07-23 22:42:28
【问题描述】:
import java.util.ArrayList;

public class FizzBuzz{

    public static void main(String[] args){
        System.out.println(fizzBuzz(15));
    }

    public ArrayList<String> fizzBuzz(int n) {
        ArrayList<String> results = new ArrayList<String>();
        for (int i = 1; i <= n; i++) {
            if (i % 15 == 0) {
                results.add("fizz buzz");
            } else if (i % 5 == 0) {
                results.add("buzz");
            } else if (i % 3 == 0) {
                results.add("fizz");
            } else {
                results.add(String.valueOf(i));
            }
        }
        return results;
    }
}

我正在尝试打印 FizzBu​​zz 数组。但是,为什么我不能在这里通过名称调用下面的方法?有人可以帮我吗?欣赏!

【问题讨论】:

标签: java arrays methods


【解决方案1】:

你可以先实例化一个对象,然后调用它的方法。像这样:

import java.util.ArrayList;

public class FizzBuzz{

    public static void main(String[] args){
        FizzBuzz obj = new FizzBuzz; //Create an instance
        System.out.println(obj.fizzBuzz(15)); //Call the mouthed through that
    }

    public ArrayList<String> fizzBuzz(int n) {
        ArrayList<String> results = new ArrayList<String>();
        for (int i = 1; i <= n; i++) {
            if (i % 15 == 0) {
                results.add("fizz buzz");
            } else if (i % 5 == 0) {
                results.add("buzz");
            } else if (i % 3 == 0) {
                results.add("fizz");
            } else {
                results.add(String.valueOf(i));
            }
        }
        return results;
    }
}

更简单的方法是将fizzbuzz() 方法更改为静态,但这不是一个好主意

现在您将使用上述任一方法获得所需的输出

[1, 2, fizz, 4, buzz, fizz, 7, 8, fizz, buzz, 11, fizz, 13, 14, fizz buzz]

【讨论】:

    【解决方案2】:

    解决此问题的一种方法是将您的方法更改为静态:

    public static ArrayList<String> fizzBuzz(int n) {
        //...
    

    如果你从主方法调用一个方法,它必须是静态的,因为main方法是static,而static方法只能引用static对象。


    但更好的做法是创建你的类的实例,然后通过你的类的实例调用方法:

    public static void main(String[] args){
        FizzBuzz fb = new FizzBuzz();
        ArrayList<String> result = fb.fizzBuzz(15);
        System.out.println(result);
    }
    

    这样您就不必创建方法static


    无论哪种方式,您都可以获得相同的输出,但第二种选择更专业、更整洁,并且完全是一种更好的做法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多