← Java tutorials

LESSON 07 / 40 · FREE TUTORIAL

Night Falls: if or else?

Let the program choose to act according to conditions

90–110 minutesJava 11+Getting Started · Conditional Judgment

WHAT YOU WILL MAKE

Making a Nighttime Survival Advisor

From a conditional door to a complete decision-making chain: distinguish multiple reminders and one main suggestion, check the rules with boundary values, and finally complete a night survival consultant that can understand the answers.

Before you start: It is recommended to complete Lessons 1–6 first

01 / 15

A door without walls

As soon as the sun hid behind the mountain, Steve stuck the door in the grass: "Safe house, completed!" Alex pointed to both sides of the door: "Where are the walls?" A zombie walked around the door, as if praising the ventilation design of the house.

Procedures also require clear thresholds. What do you do when it’s dark, what do you do when your life is low, and what do you do first when both things happen at the same time? In this lesson, we write the vague "it depends" into a rule that can be checked.

  • When the condition of if is true, which statements will be executed?
  • Is the writing method of reminding all missing equipment the same as selecting only one priority action?
  • When life happens to be 0, 8, or 9, why are the results different?

02 / 15

if: Act only when the condition is met

if can be read as "if". The boolean value must be obtained within the parentheses, and the curly braces enclose what is to be done when the condition is met. The program is only judged once when it is executed here; if the variables change later, this code will not be automatically repeated.

Complete program: Save as HealthAlert.java

public class HealthAlert {
    public static void main(String[] args) {
        int health = 7;
        if (health <= 8) {
            System.out.println("Supply first");
        }
        System.out.println("End of inspection");
    }
}

Output

Supply first
End of inspection
Conditional door: two roads finally meet

health <= 8 ?

ConditionPath
trueOutput "supply first"
falseSkip supply statement

↓ Both paths output "Check End"

03 / 15

else: Otherwise go another way

If you want to do something even when the condition is not true, add else. The same if / else judgment only goes one way, like a mine cart crossing a fork in the road, and it will not copy another one of itself.

Snippet: place inside main and run separately

boolean isNight = true;
if (isNight) {
    System.out.println("Return to the house to rest");
} else {
    System.out.println("Collection during the day");
}

Output

Return to the house to rest

Snippet: place inside main and run separately

int diamonds = 2;
if (diamonds >= 3) {
    System.out.println("The number of diamonds is enough");
} else {
    System.out.println("Not much." + (3 - diamonds) + "diamonds");
}

Output

Not much.1diamonds

04 / 15

else if: The order is also a rule

A branch chain is checked from top to bottom. If the first branch whose condition is true is selected, the subsequent branches will no longer be checked. Deal with more urgent and specific situations first, and don't let one broad condition swallow up the narrow conditions that follow.

Snippet: place inside main and run separately

int health = 7;
if (health <= 0) {
    System.out.println("Reborn.");
} else if (health <= 8) {
    System.out.println("Eat something quickly");
} else {
    System.out.println("Continue the adventure");
}

Output

Eat something quickly
Select only one: Find the entrance from top to bottom
Check in orderOn a match
health <= 0 ?Reborn.
health <= 8 ?Eat something quickly
elseContinue the adventure

Check from top to bottom; execute only the first matching branch.

05 / 15

Turn small conditions into big problems

First explain the conditions clearly in one sentence
  1. && andBoth conditions are met: it is dark and there is no shelter.
  2. || orAt least one item is satisfied: having a key or being the owner.
  3. ! NegationTurn true and false over: !hasShelter means no shelter.

Snippet: place inside main and run separately

boolean isNight = true, hasShelter = false;
if (isNight && !hasShelter) {
    System.out.println("Build temporary shelter first");
}

Output

Build temporary shelter first

Snippet: place inside main and run separately

boolean hasKey = false, isOwner = true;
if (hasKey || isOwner) {
    System.out.println("The door is open");
}

Output

The door is open

Snippet: place inside main and run separately

String weather = " RAIN ".strip();
if ("rain".equalsIgnoreCase(weather)) {
    System.out.println("Move the construction plan indoors");
}

Output

Move the construction plan indoors

06 / 15

Multiple reminders, or one main suggestion?

Lack of bread and shield can remind you of two things; deciding "what to do now" may only require one main suggestion. Determine the task first, then choose an independent if or branch chain.

Snippet: place inside main and run separately

int health = 6;
if (health <= 8) {
    System.out.println("Bring bread");
}
if (health <= 16) {
    System.out.println("With shield");
}

Output

Bring bread
With shield

Snippet: place inside main and run separately

int health = 6;
if (health <= 8) {
    System.out.println("Bring bread");
} else if (health <= 16) {
    System.out.println("With shield");
}

Output

Bring bread
Same conditions, different organizational methods
  1. Two independent ifEach of the two conditions is checked once, and two reminders may be output.
  2. An if / else if chainAfter selecting the previous item, the following conditions will no longer be checked.

07 / 15

Bug loves to sit on the threshold

Just because 7 can run correctly does not mean that 8 is also correct. First define the legal range of life, and then divide it into several levels without omissions and repeated hits. Each threshold tests itself and its neighbors on both sides.

Snippet: place inside main and run separately

int health = 8;
if (health < 0 || health > 20) {
    System.out.println("Life range error");
} else if (health == 0) {
    System.out.println("Reborn.");
} else if (health <= 8) {
    System.out.println("Low life");
} else if (health <= 16) {
    System.out.println("Proceed with caution");
} else {
    System.out.println("Sufficient life");
}

Output

Low life
Life classification: write the test points next to the rules
Input rangeThe results of this lessonrepresents the test value
Out of rangeLife range error-1、21
0Reborn.0
1 to 8Low life1、8
9 to 16Proceed with caution9、16
17 to 20Sufficient life17、20

08 / 15

Nesting: Find a room after entering the village

First ask if it is night, and then ask if there is a residence in the night branch. This is nesting. Indentation helps us see the hierarchy, and curly braces really determine which statements belong to which layer.

Snippet: place inside main and run separately

boolean isNight = true, hasShelter = false;
if (isNight) {
    if (hasShelter) {
        System.out.println("Return to the house to rest");
    } else {
        System.out.println("Build temporary shelter first");
    }
} else {
    System.out.println("Collection during the day");
}

Output

Build temporary shelter first

Snippet: place inside main and run separately

boolean isNight = false;
String advice;
if (isNight) {
    advice = "Go home";
} else {
    advice = "Collection";
}
System.out.println(advice);

Output

Collection

09 / 15

It can run, but it may be wrong.

Logical counterexample: predict first, then find redundant symbols

boolean isNight = false;
if (isNight); { // Error demonstration: extra semicolons
    System.out.println("Close the door");
}

Output

Close the door

The semicolon is an empty statement. Here if only controls this empty statement, and the subsequent code blocks are executed independently; deleting the semicolon after the condition can be fixed.

Logical counterexample: the key was secretly changed by the program

boolean hasKey = false;
if (hasKey = true) { // Error demonstration: assignment, not comparison
    System.out.println("Open the door");
}

Output

Open the door

boolean assignment also produces a boolean result, so this error actually compiles. It is enough to change it to if (hasKey); if (health = 8) is written, the result is int, which cannot be used as a condition.

  • Check the curly braces to avoid mismatching else if.
  • Check = and ==, do not treat assignments as comparisons.
  • Check < and <= and test with a value exactly equal to the threshold.

10 / 15

Guess first, then run, and finally explain

Let each run leave you with thoughts
  1. Guess firstWrite down the output and hit branches.
  2. Run againRun only the current fragment, checking each line.
  3. ExplanationIndicate which judgment changed the route.

Snippet: place inside main and run separately

int diamonds = 3, sticks = 1;
if (diamonds >= 3 && sticks >= 2) {
    System.out.println("The materials are ready");
} else {
    System.out.println("The materials are not yet complete");
}

Snippet: place inside main and run separately

int health = 8;
if (health <= 8) {
    health += 2;
}
if (health > 8) {
    health += 1;
}
System.out.println(health);

Check answers

The first question outputs "the materials are not complete" because there is only one wooden stick. The second question outputs 11: the first time it turns 8 into 10, the second independent if reads the new value 10 and adds 1.

11 / 15

Project Blueprint: Night Survival Consultant

"Don't recommend decoration when my life is 0." Steve's needs are very reasonable. The advisor reads three lines of input each time and gives only one main suggestion; if you want to ask again, rerun the program.

Enter a priori and then make a decision
  1. Read entire lineLife, time period, residence, strip first.
  2. Check optionsTime period day/night, residence yes/no.
  3. Parse numbersparseInt and catch, then check the range.
Main suggestion priority: stop checking downwards if selected previously
Check in orderOn a match
Legal life == 0Prepare for rebirth
Legal life <= 8Go to a safe place for supplies first
Life 9 to 20Let’s look at time period and residence again

Check from top to bottom; execute only the first matching branch.

12 / 15

Consultant Code: Reading and Verification

Create new NightAdvisor.java. The complete program is printed on this page and the next page: keep them sequentially in the same file, without adding extra braces between the two pages.

NightAdvisor.java · First half, continue on next page

import java.util.Scanner;

public class NightAdvisor {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Life 0-20: ");
        String healthText = in.nextLine().strip();
        System.out.println("Period day/night: ");
        String time = in.nextLine().strip();
        System.out.println("Have a place to live yes/no: ");
        String home = in.nextLine().strip();
        boolean timeOK = "day".equalsIgnoreCase(time)
                || "night".equalsIgnoreCase(time);
        boolean homeOK = "yes".equalsIgnoreCase(home)
                || "no".equalsIgnoreCase(home);
        if (!timeOK || !homeOK) {
            System.out.println("The option is wrong, please check the time period and residence");
        } else {
            try {
                int health = Integer.parseInt(healthText);
                boolean isNight = "night".equalsIgnoreCase(time);
                boolean hasShelter = "yes".equalsIgnoreCase(home);

All three inputs are read with nextLine to avoid leaving the end of the line when mixing nextInt. timeOK and homeOK first confirm that the words are legal; then convert night and yes to true after passing.

13 / 15

Consultant Code: Selection and Finishing

NightAdvisor.java · Next to the previous page

                if (health < 0 || health > 20) {
                    System.out.println("Life must be 0 to 20 between");
                } else if (health == 0) {
                    System.out.println("Life is exhausted, prepare for rebirth");
                } else if (health <= 8) {
                    System.out.println("Go to a safe place for supplies first");
                } else if (isNight) {
                    if (hasShelter) {
                        System.out.println("Return to the house to rest");
                    } else {
                        System.out.println("Build temporary shelter first");
                    }
                } else {
                    System.out.println("Collect during the day, don’t forget to bring supplies");
                }
            } catch (NumberFormatException e) {
                System.out.println("Please enter life 0 to 20 integer");
            }
        }
    }
}

try/catch follows the parsing method of Lesson 6. If you enter abc, a decimal, or a large number that cannot fit into an int, catch will give an integer prompt. After the input is legal, this branch chain will only output one main suggestion.

14 / 15

Acceptance: Only change one input at a time

Only move one variable and observe the route changes
  1. 8 / night / yesGo to a safe place for supplies first
  2. 9 / night / yesReturn to the house to rest
  3. 9 / night / noBuild temporary shelter first
Consultant test form
Life / Period / ResidenceExpected main results
0 / day / yesLife is exhausted, prepare for rebirth
20 / day / noCollect during the day, don’t forget to bring supplies
-1 or 21/day/yesLives must be between 0 and 20
abc, 8.5 or too large integer / day / yesPlease enter an integer from 0 to 20 for life
9 / nite / yesThe option is wrong, please check the time period and residence
9 / night / maybeThe option is wrong, please check the time period and residence

Let testing be evidence

  • Test 1, 8, 9, and 20 again to confirm that each main suggestion is accessed.
  • Try blanks at both ends and uppercase NIGHT / YES to confirm that cleanup and ignore case take effect.
  • When life and options are wrong at the same time, the option error is reported first according to the agreement.
  • Each row records the input, prediction, actual result, and reason for the variance.

15 / 15

Put judgment skills into your backpack

Wooden Pickaxe Task: Diamond Quantity Check

Use variables first, then connect to keyboard input. If a negative number reports an error, at least 3 will be reported as enough, otherwise the difference will be calculated. Test - 1, 0, 2, 3, 4; 2 should be 1 less.

Iron Pickaxe Mission: Life Fourth Gear Broadcast

The range is limited to 0 to 20, divided into 0, 1 to 8, 9 to 16, 17 to 20, and only one gear is output. Check with nine boundary test values ​​and explain why only the last one is left in the last else.

Diamond Pickaxe Mission: Weather and Equipment Consultant

Read clear, rain, thunder and yes/no. Verify first, then deal with thunderstorms and shelter, and finally give general weather advice. When adding armor conditions, write down the priorities first and test at least 6 groups.

Technical check: Oracle Java Language Specification Chapter 14, if, code blocks and local variables.
https://docs.oracle.com/javase/specs/jls/se21/html/jls-14.html

TAKE IT WITH YOU

Take the lesson offline

The complete lesson, code, diagrams and exercises, in your preferred language.