【问题标题】:passing boolean value between class not working as intended在类之间传递布尔值未按预期工作
【发布时间】:2018-09-17 23:52:30
【问题描述】:

我正在制作战舰游戏 我有 3 个班级和一个司机。

在播放器类中

我有这个方法

public  void hitownshiporGrenade(String[][] grid, String attack) {
    // checking if attack hits our ship, appropriate
    // if it does place an s in the  array

    if (attack.equals(s1)) {
        // -97 gives us a starting point at 0 for 'a' to
        // store in array, same for 49 and '1'
        grid[attack.charAt(0) - 97][attack.charAt(1) - 49] = "s "; 
        System.out.println("ship hit!");                                                            
        s1Sunk = true;
    }

我有声明的变量和顶部的吸气剂

private boolean s1Sunk; 
public boolean isS1Sunk() {
    return s1Sunk;
}

现在在我的另一堂课

Player player = new Player();
System.out.println(player.isS1Sunk());

如果我在驱动程序中的方法中调用它,即使第一个方法条件使其为真,它仍然是错误的;

【问题讨论】:

  • 当您创建Player 的新实例时,它不会与Player 的其他实例共享其状态,它们都可以有自己的isS1Sunk 值。这就是 MVC 中的“模型”如此重要的地方。您需要与所有需要使用它的类共享“模型”。这也是Passing Information to a Method or a Constructor涵盖的概念
  • 这样想:每次你说“新玩家”时,你都是在创建一个新玩家,所以除非你的战舰版本有很多玩家,否则你可能不应该多次调用 new。而是保存并共享 2 个玩家对象(仅调用“new”两次)
  • 哦该死的,我在类中创建了很多新对象来传递方法......我对如何在没有类 name.method 的情况下传递参数有点困惑?抱歉,这是我的第一个真正的 oop 课;(

标签: java class boolean


【解决方案1】:

假设您在代码示例中提到的方法都属于相同的Player 类定义,然后通过这样做创建Player 的新类实例(对象)

Player player = new Player();

您创建了一个新的、独立的(与所有其他的)Player 类实例。除非您为该 SPECIFIC 对象运行 hitownshiporGrenade,否则它的变量不会改变。


考虑以下几点:

Player player1 = new Player(); //player1.isSunk is false
Player player2 = new Player(); //player2.isS1Sunk is again false,
                               //and separate from player1.isS1Sunk
player1.hitownshiporGrenade(foo, bar) //This changes player1.isSunk to true
System.out.print(player1.getIsSunk());    //true, assuming lucky hits
System.out.print(player2.getIsSunk());    //false

我还建议您阅读有关正确使用 Camel case when naming your variables 的内容!这将使您的代码更易于阅读,并在您阅读时省去很多麻烦。

【讨论】:

  • @Sacha E 如果您的问题已解决,请考虑接受我的回答并将您的问题标记为已解决,方法是单击 upvote/downvote 按钮下的勾选 ✓ 按钮。
猜你喜欢
  • 2015-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-07
  • 2019-01-06
  • 1970-01-01
  • 2017-12-18
  • 1970-01-01
相关资源
最近更新 更多