在 greenfoot 中打印计分器。输出零

Printing a score counter in greenfoot. Outputting zero

我正在尝试在 greenfoot IDE 中输出分数并且一切正常(分数在增加),直到我尝试打印它。当我尝试打印它时,由于某种原因它变为零。

螃蟹Class:

public class Crab extends Animal
{
    int health = 10;
    int score = 0;
    public void act()
    {
        score = score + 1;
        System.out.println(score);
        //JOptionPane.showMessageDialog(null, newscore, "You lose!", JOptionPane.WARNING_MESSAGE);
        if (Greenfoot.isKeyDown("Left"))
        {
            turn(-3);
        }
        if (Greenfoot.isKeyDown("Right"))
        {
            turn(3);
        }
        if (canSee(Worm.class))
        {
            eat(Worm.class);
        }
        move();
        healthBar();
    }
    public void healthBar()
    {
        if (atWorldEdge())
        {
            Greenfoot.playSound("pew.wav");
            move(-20);
            turn(180);
            health = health - 1;
        }
        if (health <= 0)
        {
            Message msgObject = new Message();
            msgObject.youLose();
            Greenfoot.stop();
        }
    }
}

留言Class:

public class Message extends Crab
{
    /**
     * Act - do whatever the Message wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void youLose() 
    {
        JOptionPane.showMessageDialog(null, "Try again next time. Your score was  " + score, "You lose!", JOptionPane.WARNING_MESSAGE);
    }    
}

在 act 方法中,当我尝试打印分数时,它显示它正在增加,但是当我用 JOptionPane 打印出来时,或者在程序结束时正常打印它时,它给了我 0.

示例:

http://i.imgur.com/St0HARX.png

您正在创建一个全新的对象来调用您的 youLose() 方法。通过这样做,您的计分器将再次设置为零。您可以尝试通过为 Message 创建一个允许通过分数的新构造函数来解决这个问题。

public Message(int score) {
    this.score = score;
}

PS:我不明白为什么让你的 Message class 继承自 Crab

会有用