我有一个数组:
private String[] gamesArray = new String[] {"spin", "tof"};
当我启动程序时,我希望程序打印数组中的项目:
Please select a game: spin, tof.
这是我的尝试:
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);
}
}
}
错误:
src\Main.java:15: error: non-static variable gamesArray cannot be referenced fro
m a static context
for (String s : gamesArray) {
^
有什么问题?
答案 0 :(得分: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
您可能希望“请选择游戏”在循环之外。
答案 1 :(得分: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
class 如果要直接访问实例变量,则可以在实例方法中访问它们,而不是静态方法。
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
}
}
答案 2 :(得分:0)
GamesArray是您班级的实例成员。由于main方法始终是静态的,因此没有类的实例可以获得gamesArray。考虑使gamesArray静态