Lesson 3 of 10

Conditionals

Goal

Branching with if, switch and the ternary operator

01

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;.

02

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
  1. grade returns A from 90 to 100
  2. grade checks the cutoffs in the right order
  3. grade returns F below 60, and "?" outside the range
  4. move works with lower and upper case letters
  5. move returns "idle" for any other key
  6. damage doubles on a critical hit
03

Hints

0/3
Track lessons0 of 10 done

Java is the language behind Android apps and large systems. Everything in it lives inside a class, and you state every variable's type explicitly.

Beginner level, 10 lessons, 2 hours in total.

Main.java
OutputJava 13 (Judge0)

Compiling and running your code on the server.

–/6

Compiling and running your code on the server.

6 checks listed under “Your task”.

Track lessons0 of 10 done

Java is the language behind Android apps and large systems. Everything in it lives inside a class, and you state every variable's type explicitly.

Beginner level, 10 lessons, 2 hours in total.