Intro to Java week 3
CONDITIONALS.JAVA

Conditionals

Making the program choose.

Download week 3 Ten files, one per problem. Unzip once and open them in sequence.

How a chain runs

Drag the HP. Watch which branch fires.

80
if (hp > 66) → "Healthy"
else if (hp > 33) → "Hurt"
else if (hp > 0) → "Critical"
else → "Dead"
The one rule

A chain stops at the first branch that is true. Everything below it is skipped without being checked.

Predict the output

On paper, before running.

// 1
int hp = 12;
if (hp > 10) {
    System.out.print("Healthy ");
}
System.out.print("Done");
// 2
int hp = 3;
if (hp > 10) {
    System.out.print("Healthy ");
} else {
    System.out.print("Hurt ");
}
System.out.print("Done");
// 3
int coins = 50;
if (coins >= 10) {
    System.out.println("Bronze");
} else if (coins >= 100) {
    System.out.println("Silver");
} else if (coins >= 500) {
    System.out.println("Gold");
}
// 4
int lives = 3;
if (lives == 0);
{
    System.out.println("Game over");
}
// 5
int x = 7;
if (x > 5 && x < 10) {
    System.out.println("In range");
}
if (x < 5 || x > 6) {
    System.out.println("Outside the middle");
}

6. In number 3, what changes would allow 500 coins to print Gold?

Fix the bugs

All three compile. All three are wrong.

Bug 1

Bug1.java
Expected
Typing dragon prints Access granted
Actual
Always prints Access denied
String password = input.next();

if (password == "dragon") {
    System.out.println("Access granted");
} else {
    System.out.println("Access denied");
}

Fix it and write one sentence explaining the problem.

Hint

For text, == does not compare the letters. The method that does appeared earlier.

Bug 2

Bug2.java
Input
score = 95
Expected
A
Actual
D
if (score >= 60) {
    grade = "D";
} else if (score >= 70) {
    grade = "C";
} else if (score >= 80) {
    grade = "B";
} else if (score >= 90) {
    grade = "A";
}

Fix it and write one sentence explaining the problem.

Hint

Put 95 into the tracer at the top of this page and watch where it stops.

Bug 3

Bug3.java
Input
hp = 100
Expected
nothing printed
Actual
Respawning...
if (hp <= 0)
    System.out.println("You died.");
    System.out.println("Respawning...");

Fix it and write one sentence explaining the problem.

Hint

Without braces an if controls exactly one line. The indenting is a lie, Java ignores it.

Problems

1. Level checker

LevelChecker.java

Ask for XP, print the level.

XPLevel
1000 or more4
500 to 9993
100 to 4992
under 1001
Example
Enter your XP: 620
Level 3
Hint 1

One chain, not four separate if statements. Four separate ones print several levels at once.

Hint 2

Start from the biggest number and work down.

2. Magic 8-Ball

MagicEightBall.java

Ask a question, ignore the answer, print a random reply.

Use this line
int randomNumber = (int) (Math.random() * 5);
Then map the number to a reply
randomNumberprints
0It is certain.
1Signs point to yes.
2Ask again later.
3Don't count on it.
4Very doubtful.
Example
Ask me anything: Will I pass the test?
Signs point to yes.
Work this out

Math.random() gives a decimal from 0 up to, but never reaching, 1. Why does * 5 and a cast to int produce 0 to 4? What change produces 1 to 10?

Hint

Store the number in a variable once, then run the chain on that variable. Calling Math.random() inside every branch produces a different number each time and the answers go strange.

3. One-shot guessing game

GuessingGame.java

Secret number 1 to 10. One guess. Say too high, too low, or right. Off by exactly 1 also counts as close. Always reveal the answer.

Example
Your name: Sam
Guess 1-10, Sam: 7

Too high!
But you were close.
It was 6.
Hint 1
int secret = (int) (Math.random() * 10) + 1;
Hint 2

"Close" is a separate question from "too high". Two if blocks, not one chain.

Hint 3

Read the name first, the number second, and it works:

System.out.print("Your name: ");
String name = input.nextLine();

System.out.print("Guess 1-10, " + name + ": ");
int guess = input.nextInt();

The other way round breaks. After nextInt() the Enter key you pressed is still sitting there waiting, so the next nextLine() grabs that instead of what you type. If you ever hit this, add one extra input.nextLine(); to swallow it.

4. Text adventure

Dungeon.java

Two doors, two different rooms. Change the player's HP or gold in at least one, then print their status.

Example
A corridor splits. Left or right? left
A goblin clips you for 10.
HP 90, gold 0.
Hint

Use .equals() to compare what they typed, never ==.

Now try typing Left with a capital L. It breaks. There is a second method that fixes it, .equalsIgnoreCase(), which treats Left and left as the same. Switch to it after seeing the capital L fail.

5. Leap year

LeapYear.java

Optional. Divisible by 4 is a leap year, unless also divisible by 100, unless also divisible by 400.

Examples
Year? 2024        Year? 1900          Year? 2000
Leap year.       Not a leap year.   Leap year.
Hint 1

year % 4 == 0 asks whether a year divides by 4 exactly.

Hint 2

A nested if is easier to get right. A single condition with && and || also works and is very satisfying once it clicks. Nested first.

Rules

  1. Braces on every if, even one-line bodies.
  2. No semicolon after the ) of an if.
  3. Name, date and one sentence at the top of every file.
  4. Only what you have been taught. No loops, no switch, no methods other than main.
  5. Stuck fifteen minutes on one thing? Stop and ask.