0

I'm tasked with creating a java game in Greenfoot. I would like to collect 5 coins, a door appears, you enter the door, next level. I've done that so far. There's a problem with this if/else statement I think:

if (coinsCollected == 5 && levelCounter == 0) {
    getWorld().addObject(new door_temp(), 157, 162);
    levelCounter += 1;
    coinsCollected = 0;
    secondLevel();
}

if (coinsCollected == 5 && levelCounter == 1) {
    getWorld().addObject(new door_temp(), 961, 170);
    levelCounter += 1;
    coinsCollected = 0;
    thirdLevel();
}

For some reason, even if I'm on level 2 and I touch the door, the first statement gets executed. I don't understand why though because I increment levelCounter by one each time.

Thanks to anyone that can help ;)

  • To be certian, I would add print statement for the level counter as the first line of each if statement, for example: `System.out.println("in block 1, levelCounter is: " + levelCounter);` – sleepToken Nov 23 '19 at 14:15
  • ok so I did that for statements and got this for the first "levelCounterlevelCounter" but the second I got "levelCounterlevelCounterlevelCounter". @sleepToken –  Nov 23 '19 at 17:16
  • needless to say, "levelCounter" is not equal to 1 *or* 0. Are you sure it's an int? not a String? – sleepToken Nov 23 '19 at 17:25
  • ```private int coinsCollected = 0; private int levelCounter = 0;``` No its defenitely an int @sleepToken –  Nov 23 '19 at 17:34
  • Something is going on, because when you "increment" it by one, it's just appending itself. You need to figure out why printing it doesn't spit out 1 or 0. I can't help any further without a [reprex], at this point I'm just taking your word for it – sleepToken Nov 23 '19 at 17:36
  • Do you think it's anything to do with private? @sleepToken –  Nov 23 '19 at 17:40
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/202945/discussion-between-herbie-vine-and-sleeptoken). –  Nov 23 '19 at 17:44

1 Answers1

0

Your statement isn't actually an if/else, so as it stands it will execute both parts when you touch the door on level 0 (assuming secondLevel() returns).

I suspect the problem is that levelCounter is declared as an instance variable in the world class for level 1, but when you move to level 2, the instance variable for that world class is 0 again. But it depends how you've implemented levels and which class the above code is in. A lot more code is needed to be sure of the problem.

Neil Brown
  • 3,558
  • 1
  • 27
  • 36
  • I see what you mean, but I declared *coinsCollected* in the player class. I checked throughout my game to see if that was true, and YES! Every time I go to the next level, *coinsCollected* resets to 0. How would I fix this problem? –  Nov 24 '19 at 12:03