Help with bookkeeper

Hello,

I try to find the issue in my code for 2 days now but i cant find it… it collect the coins and break after 30 secounds, go to the npc and says for example 15 instead of 19… i wirte in java.

// Fight enemies for 15 seconds.
// Keep count whenever an enemy is defeated.
var defeated = 0;
var totalGold = 0;
while (true) {
    var enemy = hero.findNearestEnemy();
    if (enemy) {
        hero.attack(enemy);
        if (enemy.health <= 0) {
            defeated += 1;
        }
    }
    if (hero.now() > 15) {
        break;
    }
}

// Tell Naria how many enemies you defeated.
hero.moveXY(59, 33);
hero.say(defeated);

// Collect coins until the clock reaches 30 seconds.
while(true) {
    var coin = hero.findNearestItem();

    if (coin) {
        var x = coin.pos.x;
        var y = coin.pos.y;
        hero.moveXY(x, y);
        totalGold += coin.value;
    }
    if (hero.now() > 30){
        break;
        }
}
// Tell Naria how much gold you collected.
hero.moveXY(59, 33);
hero.say(totalGold);

// Fight enemies until the clock reaches 45 seconds.
// Remember to reset the count of defeated enemies!
while(true) {
    var enemy = hero.findNearestEnemy();
    if (enemy){
        hero.attack(enemy);
        if (enemy.health >= 0){
            defeated += 1;
            }
        }
    if (hero.now() > 45){
        break;
        }
}

// Tell Naria how many enemies you defeated.
hero.moveXY(59, 33);
hero.say("defeated");

Could you post your code correctly, as a code, not as a text?
FAQ - Check Before Posting

Done (was my first post)

Don’t count totalGold, use hero.gold. Because coin appears often and it’s possible that new coins appear while you are coming to take the nearest. As the result you collect more than you counted.

I’m having the same problem with python. I tried your suggestion Bryukh but it just returns a ridiculous number like 116.

Any suggestions?

# Fight enemies for 15 seconds.
# Keep count whenever an enemy is defeated.
defeated = 0
while True:
    enemy = hero.findNearestEnemy()
    if enemy:
        hero.attack(enemy)
        if enemy.health <= 0:
            defeated += 1
    if hero.time > 15:
        break

# Tell Naria how many enemies you defeated.
hero.moveXY(59, 33)
hero.say(defeated)

# Collect coins until the clock reaches 30 seconds.
CoinCollected = 0
while True:
    coin = hero.findNearestItem()
    if coin:
        hero.moveXY(coin.pos.x, coin.pos.y)
        CoinCollected += hero.gold
    if hero.time > 30:
        break

# Tell Naria how much gold you collected.
hero.moveXY(59, 33)
hero.say(CoinCollected)

# Fight enemies until the clock reaches 45 seconds.
# Remember to reset the count of defeated enemies!
defeated - 0
while True:
    if enemy:
        hero.attack(enemy)
        if enemy.health <= 0:
            defeated += 1
    if hero.time > 45:
        break
        
# Tell Naria how many enemies you defeated.
hero.moveXY(59, 33)
hero.say(defeated)

I see my mistake… fixed