IF语句Java问题

时间:2013-04-06 12:04:53

标签: java if-statement

我创建了一个名为multiplay的布尔值。

private boolean multiplay;

我的public Game()内有:

// make a player
player = new Player(this);
if(multiplay == true) {
   player2 = new Player(this);
}

在实际的类文件中,我创建了一个方法:

public void startMutliPlayer() {
   multiplay = true;
}

我要做的是当调用startMultiPlayer时,它会将布尔multiplay设置为true,因此,两个玩家将被添加到框架而不是一个。如果没有调用'startMultiPlayer',它只会添加一个播放器。

目前,当我拨打startMultiPlayer时,它只会添加一个不是两个的玩家。

更新:

能够使用以下代码对此问题进行排序:

// Make Players (Single & MultiPlayer)
        if (multiplay == false) {
            player = new Player(this);
            player.setPosition(startPosition);
            player.move(new Vec2(-210, 0));
            multiplay = true;
        } else if(multiplay == true) {
            player = new Player(this);
            player.setPosition(startPosition);
            player.move(new Vec2(-210, 0));player2 = new Player(this);
            player2.setPosition(startPosition);
            player2.move(new Vec2(-150, 0));
            multiplay = false;
        }

public static void startMutliPlayer() {
        multiplay = false;
    }

由于

3 个答案:

答案 0 :(得分:0)

Game类中创建一个方法,即

public void setMultiplay(boolean multiplay) {
  this.multiplay = multiplay; // scope
  if (multiplay) {
    player2 = new Player(this);
  }
}

答案 1 :(得分:0)

Game类的哪个对象是你在调用startMultiPlay?因为在调用Game构造函数之后它总会被调用,所以它不起作用 - 因为当调用Game ctor时,multiplay将是false。

解决这个问题的方法是

private boolean multiplay;

需要更改为

private static boolean multiplay;

还要将startMultiPlayer设置为静态,并在创建Game对象之前调用它。

另一种方法是不在Game的ctor中创建Player。 必须使用方法startMultiPlayer和startSinglePlayer - 分别在这些方法中创建一个或两个Player对象。

答案 2 :(得分:0)

我猜你在Game类的一个对象上调用方法startMultiPlayer()。 但是,构造函数是在Java中创建对象时要执行的第一件事。     游戏=新游戏();     game.startMultiPlayer(); 将按此顺序执行以下行:

// make a player
player = new Player(this);
if(multiplay == true) {
   player2 = new Player(this);
}
multiplay = true;

这意味着在检查是否为真后,将multiplay设置为true。因此,您仍将处于单人游戏模式。

在调用(或不调用)startMultiPlayer()方法后,尝试检查multiplay是否为真。

另请注意,您只需编写if(multiplay)而不是if(multiplay==true),因为Java中的if语句只能使用布尔值。但这是个人偏好,无论如何都可能会自动优化。