Start learning free

LESSON 99 OF 291 · CONDITIONAL STATEMENTS - CHALLENGES

Top K Brands V2 in Scala: The Better of Two Brands

Practice Read the full explanation

Two brands sell the same product. Show the one with the higher rating.

You start with:

        val brand1 = "TechPro"
        val rating1 = 4
        val brand2 = "MegaCorp"
        val rating2 = 5

        var bestBrand: String = ""
        var bestRating: Int = 0

Build:

1. MegaCorp (5)

Rules:

  • Use if/else to pick the winner: brand1 when rating1 > rating2, otherwise brand2.
  • The starter already declares bestBrand and bestRating: assign the winner's name and rating to them inside the branches.
  • Format the result as "1. Brand (rating)" and print it with println(...).

Pick the winner into bestBrand and bestRating first, then build the output text from them.

Scala's + on a String and an Int converts the number to text for you.

        val brand1 = "TechPro"
        val rating1 = 4
        val brand2 = "MegaCorp"
        val rating2 = 5

        var bestBrand: String = ""
        var bestRating: Int = 0
        if (rating1 > rating2) {
            bestBrand = brand1
            bestRating = rating1
        } else {
            bestBrand = brand2
            bestRating = rating2
        }
        println("1. " + bestBrand + " (" + bestRating + ")")

STEP 1 OF 5
    Ctrl + Enter to check

    SCALA · CONDITIONAL STATEMENTS - CHALLENGES

    Top K Brands V2 in Scala, explained

    Problem overview

    Two brands sell the same product: brand1 with rating1 and brand2 with rating2. The program must show the one with the higher rating, formatted as a ranked entry, 1. Brand (rating). The starter code also declares two variables for the winner, bestBrand and bestRating, set to placeholders.

    With TechPro rated 4 and MegaCorp rated 5, MegaCorp wins:

    1. MegaCorp (5)
    

    The previous version printed a single brand. Now the program has to decide which brand to print.

    Approach: let the branches fill the winner variables

    Ask one question: is rating1 strictly greater than rating2? If it is, brand 1 is the winner. In every other case, brand 2 is: it has the higher rating, or the two ratings are equal. So an if/else covers every situation with a single comparison.

    Each branch copies both the name and the rating of the winner into bestBrand and bestRating. After the if/else, one println formats whichever brand was stored. The formatting is written once, not once per branch.

    The 1. at the start of the line is the rank. Only the best brand is printed, so the rank is always 1 and stays a fixed piece of text in the output string. Only the brand and the rating come from the variables.

    Keeping the winner's rating in its own variable, next to the name, means the final line never has to repeat the comparison to find out which brand won: whichever branch ran, the two variables already agree.

    Step by step

    1. The condition. Write if (rating1 > rating2) {. The variables bestBrand and bestRating already exist from the starter code, so this version only assigns them.
    2. Brand 1's name. Inside the if, set bestBrand = brand1.
    3. Brand 1's rating. Still inside, set bestRating = rating1. A name and its rating travel together, so set both before leaving the branch.
    4. The else. Close the if body with } else { and set bestBrand = brand2. Write the final } right away.
    5. Brand 2's rating. Inside the else, set bestRating = rating2.
    6. Print. After the if/else, print "1. ", bestBrand, " (", bestRating and ")" joined with +.

    Following the program

    With the starter data, the condition asks whether 4 > 5. It is false, so the else branch runs. The two variables change like this:

    MomentbestBrandbestRating
    After the declarationsempty text0
    After the else branchMegaCorp5

    The last line then joins the pieces into 1. MegaCorp (5). The placeholders never reach the output, because exactly one of the two branches always runs and overwrites both of them.

    Why the variables are declared before the if

    A variable created inside the braces of a branch exists only there. The println after the if/else couldn't see it, and the compiler would report that the name isn't found. Declaring bestBrand and bestRating first, with placeholder values, puts them in scope for the whole block, so the branches can assign them and the final line can read them. The placeholders are the "empty" values of their types: empty text for a String and 0 for an Int.

    The solution in Scala

    val brand1 = "TechPro"
    val rating1 = 4
    val brand2 = "MegaCorp"
    val rating2 = 5
    var bestBrand: String = ""
    var bestRating: Int = 0
    if (rating1 > rating2) {
        bestBrand = brand1
        bestRating = rating1
    } else {
        bestBrand = brand2
        bestRating = rating2
    }
    println("1. " + bestBrand + " (" + bestRating + ")")
    

    Scala notes:

    • var for the winner, val for the data. The ratings and names never change, but bestBrand and bestRating are assigned inside the branches, so they have to be vars.
    • Type annotations. var bestBrand: String = "" spells out the type. Scala would infer String from "" anyway, but a var starting at an empty placeholder reads better with its type written down.
    • if returns a value. The same logic can be written as val (b, r) = if (rating1 > rating2) (brand1, rating1) else (brand2, rating2), which needs no placeholder variables. It prints the same line.

    Testing

    Brand 1Brand 2Output
    TechPro, 4MegaCorp, 51. MegaCorp (5)
    TechPro, 5MegaCorp, 41. TechPro (5)
    TechPro, 4MegaCorp, 41. MegaCorp (4)

    Edge cases and common mistakes

    • Ties. The lesson's rule is "brand1 when rating1 > rating2, otherwise brand2", so equal ratings go to the second brand, as the last row of the table shows. Writing >= would give ties to the first brand and change the output for equal ratings.
    • Setting only the name. If a branch updates bestBrand but forgets bestRating, the output keeps the placeholder rating, so a winner can be printed with (0).
    • Redeclaring inside the branch. Writing var bestBrand = brand2 in a branch creates a new variable that hides the outer one, and the outer one keeps its placeholder. The program then prints 1. (0). Inside the branches, assign with bestBrand = brand2, without var.
    • Printing inside the branches. That works, but it duplicates the formatting. Storing the winner first keeps the output line in one place.
    • Comparing the wrong values. The condition compares the ratings, not the brand names. Comparing names with > would be alphabetical order, which has nothing to do with the rating.

    Key takeaways

    • One strict comparison and an else choose between two candidates.
    • Store the winner's name and rating together, then format once.
    • The branch that holds the tie decides who wins a tie: here, the else brand.
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free