I am trying to output a score in the greenfoot IDE and all is working fine (the score is increasing) until I try to print it. When I try to print it it changes to zero for some reason.
Crab 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();
}
}
}
Message 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);
}
}
In the act method when I try to print out the score it shows it is increasing but when I print it out with JOptionPane
or as normal at the end of the program it gives me 0.
Example:
You're making a completely new object to invoke your youLose()
method on. By doing this, your score-counter will be set to zero again. You could try solving this by making a new constructor for Message that allows to pass the score.
public Message(int score) {
this.score = score;
}
PS: I don't see why it would be useful to make your Message class inherit from Crab