Lesson 3 of 10
Conditionals
- 12 min
- 6 checks
- 3 hints
- Go to task
Goal
Branching with if, switch and the ternary operator
Explanation
if runs its code when its condition is true, else if adds another condition, and else takes everything left over. Java checks the branches in order and runs only the first true one, so start with the highest cutoff: if you started with score >= 60, a score of 95 would get a D. You combine conditions with && (and) and || (or).
switch compares one value against fixed values like case 'w':, and you have to end every branch with break. Otherwise execution falls through to the next branch and runs it too. Fall-through is a well-known source of bugs, but it's handy when you want several values to share one branch, like case 'w': case 'W':. default takes any value that didn't match anything.
To choose between two values in one line, use the ternary operator cond ? a : b, as in int lives = hardMode ? 1 : 3;.
Your task
Write grade(score) as a chain of if statements that returns A from 90, B from 80, C from 70, D from 60 and F below that, and returns "?" if the score is outside the range 0 to 100. Then use switch to write move(key) for the WASD keys: w returns "up", s returns "down", a returns "left" and d returns "right", whether the letter is lower or upper case, and any other key returns "idle". Finally, write damage(base, critical) with the ternary operator so it returns twice the base value on a critical hit and base itself otherwise.
Checks
6 checks- grade returns A from 90 to 100
- grade checks the cutoffs in the right order
- grade returns F below 60, and "?" outside the range
- move works with lower and upper case letters
- move returns "idle" for any other key
- damage doubles on a critical hit