我正在尝试在 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。
例子: