-1

I have an array:

private String[] gamesArray = new String[] {"spin", "tof"};

And when I start the program, I want the program to print the items in the array:

Please select a game: spin, tof.

This is my attempt:

import java.util.Scanner;

public class Main {

private Scanner console = new Scanner(System.in);
private Spin spin = new Spin();
private String input = "";
private String[] gamesArray = new String[] {"spin", "tof"};

public static void main (String[] args) {

    System.out.println("Welcome to the system!");

    for (String s : gamesArray) {

        System.out.println("Please select a game:" + s);

    }

}
}

Error:

src\Main.java:15: error: non-static variable gamesArray cannot be referenced fro
m a static context
                for (String s : gamesArray) {
                                ^

What is wrong?

4

3 回答 3

3

您正在尝试打印没有实例的实例字段。main() 方法是静态的。

您可以通过将 gamesArray 声明为静态字段来解决此问题。例如:

 private static final String[] gamesArray = new String[] {"spin", "tof"};

或者,您可以创建一个 Main() 类的实例,并通过它访问该字段。

 Main myMain = new Main();
 for (String s : myMain.gamesArray) {

完成其中一项操作后,您会注意到输出如下所示:

Please select a game:spin
Please select a game:tof

您可能希望“请选择游戏”位于循环之外。

于 2013-06-24T19:23:38.647 回答
1

您需要先创建类的对象

 Main obj = new Main();
 for(String s : obj.gamesArray){
       System.out.println("Please select a game:" + s);

 } 
  • 静态方法或变量可以直接从静态方法访问。如果您声明数组,private static String[] gamesArray = new String[] {"spin", "tof"};那么您可以在不创建Main类对象的情况下访问它
  • 但是您可以直接从实例方法访问静态变量,因为静态变量是所有实例之间的共享变量。
  • 如果你想直接访问实例变量,那么你可以在实例方法而不是静态方法中访问它们。

    public class StaticNonStatic {
    
    private static int staticVar;
    private int instanceVar;
    
    public void instanceMethod(){
        System.out.println(instanceVar);// instance variable accessed directly
        System.out.println(staticVar); // static variable accessed directly from instance method
    }
    
    public static staticMethod(){
        System.out.println(instnaceVar); // no this is wrong, can't access instance member from static block directly
        System.out.println(instnaceVar); // fair enough, accessing static member from static method directly
    }
    
    }
    
于 2013-06-24T19:24:57.213 回答
0

GamesArray 是您的类的实例成员。由于 main 方法始终是静态的,因此在 gamesArray 中没有该类的实例。考虑将 gamesArray 设为静态

于 2013-06-24T19:24:07.437 回答