Java: Brittle Morale

Hi. I am stuck on this level and can’t find the solution no matter how hard I try! Here is my code. Please can you tell me if I have any errors?

// You have one arrow. Make it count!

// This should return the enemy with the most health.
function findStrongestEnemy(enemies) {
    var strongest = null;
    var strongestHealth = 0;
    var enemyIndex = 0;
    while (enemyIndex < enemies.length) {
    var enemy = enemyIndex;
       if (enemy.health < strongestHealth) {
    enemy = strongest;
    strongestHealth = enemy.health;
    enemyIndex = enemyIndex + 1;
        }
    return strongest;
    }
}
var enemies = hero.findEnemies();
var leader = findStrongestEnemy(enemies);
if (leader) {
    hero.say(leader);
}

Hi HeroA,

Welcome to the forum!

A few things to sort out on your code (there’s some tricky new concepts at this stage in CoCo):

Firstly, for this:

‘Enemies’ is a variable that is a list of all the different enemies, and you want to set ‘enemy’ to be enemies[0] on the first loop, and then enemies[1], then enemies[2] etc. What do you need to write?

Read the comment for this again “// If enemy.health is greater than strongestHealth”. Is this what you have?

Again the comment is “// Set strongest to enemy” - is this what you have? (You’ve got them the right way round for ’
strongestHealth = enemy.health’).

Finally:

These. You want enemyIndex to update every time the while loop runs, so it wants to be outside the next bracket. You also only want to return the answer once the whole while loop has run, so again it wants to be outside the next bracket.

A couple of things that might help your coding. 1) Indentation is useful. It isn’t essential to do it right on Javascript (unlike with Python), but it can help you look at a block of code and check which commands belong in which brackets. 2) Keep the comments - they’re really useful when trying to problem solve.

Good luck - try doing the things above, and post again if you’re still stuck.

Jenny

3 Likes

Hello and welcome to codecombat discourse! This is a cozy forum where you can share ideas, share fan art, get assistance for code, etc! Before you proceed, we hope that you review this topic, which shows all essentials of this board! Thanks!

1 Like

This topic was automatically closed 12 hours after the last reply. New replies are no longer allowed.