我确定我错过了一些愚蠢的话,这是我的代码:
public class clearBlankGrid {
public static void main(String args[]) {
Monster myMonster = new Monster(10,10,5,5,1);
MonsterGUI myGUI = new MonsterGUI(myMonster);
if (myMonster.getRows() > 0) {
// 0 = North, 1 = East, 2 = South, 3 = West
myMonster.setFacing(3);
myMonster.setIcon();
}
}
public static void keepClearing() {
myMonster.isGridCleared(); // Cannot find symbol 'myMonster'
}
}
答案 0 :(得分:3)
myMonster
如果要在keepClearing
方法(静态)中访问它,则需要是静态成员。
注意:作为参考,您还可以通过实际实例化Monster
类来避免使clearBlankGrid
成员静态。 Monster
可以是clearBlankGrid
的实例变量,这意味着keepClearing
方法不再必须是静态的。
public class clearBlankGrid {
private Monster myMonster;
private MonsterGUI myGUI;
public void run() {
myMonster = new Monster(10,10,5,5,1);
myGUI = new MonsterGUI(myMonster);
if (myMonster.getRows() > 0) {
// 0 = North, 1 = East, 2 = South, 3 = West
myMonster.setFacing(3);
myMonster.setIcon();
}
}
public void keepClearing() {
myMonster.isGridCleared();
}
public static void main(String args[]) {
clearBlankGrid blankGrid = new clearBlankGrid();
blankGrid.run();
}
}
答案 1 :(得分:1)
您需要将对象放在静态字段中。
答案 2 :(得分:1)
让myMonster
成为static
班级成员:
public class clearBlankGrid {
private static Monster myMonster;
public static void main(String args[]) {
myMonster = new Monster(10,10,5,5,1);
// ...
}
}
答案 3 :(得分:0)
public class clearBlankGrid {
// I made this static because you access it via a static method.
// If you make it a class member, as Greg Hewgill suggested, then
// change the method that uses it to be non-static
private static Monster myMonster = new Monster(10,10,5,5,1);
public static void main(String args[]) {
MonsterGUI myGUI = new MonsterGUI(myMonster);
if (myMonster.getRows() > 0) {
// 0 = North, 1 = East, 2 = South, 3 = West
myMonster.setFacing(3);
myMonster.setIcon();
}
}
public static void keepClearing() {
myMonster.isGridCleared(); // Cannot find symbol 'myMonster'
}
}