ApexSensei

Drills › Write Apex

Score bands with else if

Write Apex · Beginner · 12 min · Runs in your Salesforce Developer org · Free

Scenario. Sales wants each Lead sorted into a band by score, with new Leads that have no score kept apart.

Write a method that sorts a Lead score into Hot, Warm, Cold or Unscored with if / else if / else.

What you will learn

Use if / else if / else to pick one answer from several. Apex tries each test from the top and runs only the first one that is true.

if (score >= 80) {
    band = 'Hot';
} else if (score >= 50) {
    band = 'Warm';
} else {
    band = 'Cold';
}

Gotcha. null >= 80 is false, so test for null first. Also, String == ignores case ('hot' == 'Hot' is true), but .equals() does not.

The task

Write a method scoreBand(Integer score) that returns a Lead's band: Hot, Warm, Cold or Unscored.

Examples:

  • scoreBand(80) → Hot
  • scoreBand(79) → Warm, and scoreBand(49) → Cold
  • scoreBand(null) → Unscored

Requirements:

  1. Return Unscored when the score is null. Test this first.
  2. Return Hot for 80 or more, and Warm for 50 to 79.
  3. Return Cold for anything below 50.
  4. Use if, else if and else, and keep the method's name and input. The grader calls it with more scores, some of them hidden.

Starter code

String scoreBand(Integer score) {
    return null;
}

System.debug('Score 85: ' + scoreBand(85));
System.debug('Score null: ' + scoreBand(null));

When it passes

Your method returns `Hot` for 80 and up, `Warm` for 50 to 79, `Cold` below 50, and `Unscored` for null, for every score the grader tries.

Try this drill free

You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.

‹ Working with dates · Switch on Case status ›