我正在尝试在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。
示例:
答案 0 :(得分:1)
您正在创建一个全新的对象来调用您的youLose()
方法。通过这样做,您的分数计数器将再次设置为零。你可以尝试通过为Message提供一个允许传递分数的新构造函数来解决这个问题。
public Message(int score) {
this.score = score;
}
PS:我不明白为什么让你的Message类从Crab继承是有用的