0

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

蟹类:

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();
        }
    }
}

留言类:

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

4

1 回答 1

1

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

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

PS:我不明白为什么让你的 Message 类继承自 Crab 会有用

于 2015-02-16T07:21:06.843 回答