我知道这个问题经常出现,但即使在查看问题后我也找不到解决方案..
因此,对于学校,我们必须创建一个自己的Zuul世界版本。我已经实现了一个投影仪。首先我把它放在Game类中,但我认为将它放在它自己的类Beamer中会更好。 Beamer类看起来如下:
public class Beamer
{
private Room beamerRoom;
private Room beamer;
private int timesFired;
private boolean beamerCharged;
public Beamer(int timesFired, boolean beamerCharged)
{
this.timesFired = 0;
this.beamerCharged = false;
}
public int getTimesFired()
{
return timesFired;
}
public Room getBeamerRoom()
{
return beamerRoom;
}
public boolean getBeamerCharged()
{
return beamerCharged;
}
public Room setBeamerRoom(Room room)
{
this.beamerRoom = Game.getCurrentRoom();
return beamerRoom;
}
/**
* Try to use beamer device. When you charge the beamer, it memorizes the current room.
* When you fire the beamer, it transports you immediately back to the room it was
* charged in.
*/
public void beamer(Command command){
if (!command.hasSecondWord()) {
// if there is no second word, we don't know what to do...
System.out.println("Charge or fire beamer?");
return;
}
String action = command.getSecondWord();
if (action.equals("charge")) {
if(timesFired() < 1)
{
beamerRoom = Game.getCurrentRoom();
System.out.println("This room is charged to beam!");
beamerCharged = true;
}
else
{
System.out.println("The beamer has already been fired and can't be charged again");
}
} else if (action.equals("fire")) {
if(beamerCharged == true)
{
if(timesFired < 1)
{
Game.getCurrentRoom() = beamer.getBeamerRoom();
System.out.println("The beamer has succesfully been fired!");
System.out.println(currentRoom.getLongDescription());
timesFired++;
beamerCharged = false;
}
else
{
System.out.println("You can only fire the beamer once!");
}
}
else
{
System.out.println("The beamer hasn't been charged yet!");
}
} else {
System.out.println("Invalid beamer command!");
return;
}
}
}
我在这里收到错误method getCurrentRoom() cannot be referenced from a static context
:
beamerRoom = Game.getCurrentRoom();
Game中获取当前房间的方法如下:
public Room getCurrentRoom()
{
return currentRoom;
}
很简单,在我看来应该有用。
我该如何解决这个问题?我环顾四周但找不到有效的修复方法..
如果您需要更多Game类代码,请询问。我没有在这里发布,因为它是300多行。
编辑:
我已经找到了我做错了什么。通过使用Game.getCurrentRoom
,它查看了Game类,而不是Game的对象。至少那是我认为出了问题。我有更多方法的错误消息,使用大写字母(Game.<method>
),Player.<method>
),但是当我没有使用大写字母(game.<method>
),player.<method>
时它运作良好。
所以我猜问题已经解决了。
答案 0 :(得分:0)
当您致电Game.getCurrentRoom()
时,您正试图在课程Game
上调用此方法。但是您将该方法定义为实例方法。因此,您需要更改代码以使用Game的单例实例访问其实例方法,或者您需要将Class上的mehtods声明为static。请注意,这些方法只能访问类成员,而不能访问实例成员。
public static Room getCurrentRoom()
{
return currentRoom; // currentRoom has to be declared as a private static class member
}