Module 3: Boolean Logic, Conditionals, and Enums
Module Overview
Learn about boolean logic, conditional statements, and enumerated types in Java.
Learning Objectives
- Use relational operators to compare values
- Evaluate complex boolean expressions using logical operators
- Implement conditional behavior using if-else statements
- Implement multi-way conditional logic using switch statements
- Create and use enumeration types to represent fixed sets of constants
- Use enum constants in switch statements
- Understand short-circuit evaluation in boolean expressions
Boolean Logic and Operators
Relational Operators
Relational operators compare two values and return a boolean result.
// Relational operators
int a = 5;
int b = 10;
boolean isEqual = (a == b); // false
boolean isNotEqual = (a != b); // true
boolean isGreater = (a > b); // false
boolean isLess = (a < b); // true
boolean isGreaterOrEqual = (a >= b); // false
boolean isLessOrEqual = (a <= b); // true
Logical Operators
Logical operators combine boolean expressions to create more complex conditions.
// Logical operators
boolean condition1 = true;
boolean condition2 = false;
boolean andResult = condition1 && condition2; // false (both must be true)
boolean orResult = condition1 || condition2; // true (at least one must be true)
boolean notResult = !condition1; // false (negates the value)
Short-Circuit Evaluation
Java uses short-circuit evaluation with logical operators, which means it stops evaluating an expression as soon as the result is known.
// Short-circuit evaluation
boolean result = (x != 0) && (10 / x > 1);
// If x is 0, (x != 0) is false, so (10 / x > 1) is not evaluated
// This prevents the division by zero error
Conditional Statements
If-Else Statements
If-else statements allow you to execute different code blocks based on conditions.
// Basic if statement
if (temperature > 30) {
System.out.println("It's hot outside!");
}
// If-else statement
if (score >= 70) {
System.out.println("You passed!");
} else {
System.out.println("You need to study more.");
}
// If-else-if ladder
if (grade >= 90) {
System.out.println("A");
} else if (grade >= 80) {
System.out.println("B");
} else if (grade >= 70) {
System.out.println("C");
} else {
System.out.println("Failed");
Switch Statements
Switch statements are used for multi-way branching based on the value of an expression.
// Switch statement with int
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
// ... other cases
default:
System.out.println("Invalid day");
}
// Switch statement with String (Java 7+)
String fruit = "apple";
switch (fruit) {
case "apple":
System.out.println("Red fruit");
break;
case "banana":
System.out.println("Yellow fruit");
break;
default:
System.out.println("Unknown fruit");
}
Ternary Operator
The ternary operator is a shorthand way to write simple if-else statements.
// Ternary operator
int age = 20;
String status = (age >= 18) ? "Adult" : "Minor";
// Equivalent if-else
String status;
if (age >= 18) {
status = "Adult";
} else {
status = "Minor";
}
Enumeration Types (Enums)
Creating Enums
Enums are special data types that define a set of named constants.
// Basic enum declaration
public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
// Using enum constants
Day today = Day.WEDNESDAY;
System.out.println("Today is " + today);
Enums with Properties and Methods
Enums can have fields, constructors, and methods like regular classes.
public enum Planet {
MERCURY(3.303e+23, 2.4397e6),
VENUS(4.869e+24, 6.0518e6),
EARTH(5.976e+24, 6.37814e6),
MARS(6.421e+23, 3.3972e6),
JUPITER(1.9e+27, 7.1492e7),
SATURN(5.688e+26, 6.0268e7),
URANUS(8.686e+25, 2.5559e7),
NEPTUNE(1.024e+26, 2.4746e7);
private final double mass; // in kilograms
private final double radius; // in meters
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
public double getMass() {
return mass;
}
public double getRadius() {
return radius;
}
// Universal gravitational constant
public static final double G = 6.67300E-11;
public double surfaceGravity() {
return G * mass / (radius * radius);
}
}
Enum Methods
All enums have built-in methods like values() and valueOf().
// Getting all enum values
Day[] days = Day.values();
for (Day day : days) {
System.out.println(day);
}
// Converting a string to enum constant
Day day = Day.valueOf("MONDAY"); // Returns Day.MONDAY
Enums in Switch Statements
Enums work well with switch statements for type-safe branching.
Day today = Day.WEDNESDAY;
switch (today) {
case MONDAY:
System.out.println("Start of work week");
break;
case TUESDAY:
case WEDNESDAY:
case THURSDAY:
System.out.println("Midweek");
break;
case FRIDAY:
System.out.println("End of work week");
break;
case SATURDAY:
case SUNDAY:
System.out.println("Weekend");
break;
}
Additional Resources
Practice Exercises
Complete these exercises to reinforce your understanding of boolean logic, conditionals, and enums.
Exercise 1: Traffic Light System
Create a traffic light system with the following components:
- An enum for TrafficLightColor (RED, YELLOW, GREEN)
- A TrafficLight class that tracks the current color
- Methods to change the light color based on a sequence
- A switch statement to print instructions based on the current color
Exercise 2: Student Grade Calculator
Create a grade calculator with the following features:
- An enum for GradeLevel (FRESHMAN, SOPHOMORE, JUNIOR, SENIOR)
- Methods to calculate final grades based on test scores and assignments
- Different grading scales based on the student's grade level
- Conditional logic to determine if a student passes or fails
Mastery Task 6 - Enumerating the Commands
Mastery Task Guidelines
Mastery Tasks are opportunities to test your knowledge and understanding through code. When a mastery task is shown in a module, it means that we've covered all the concepts that you need to complete that task. You will want to make sure you finish them by the end of the week to stay on track and complete the unit.
Each mastery task must pass 100% of the automated tests and code styling checks to pass each unit. Your code must be your own. If you have any questions, feel free to reach out for support.
AppSettings Update
Go to com.adventure.settings.AppSettings and update the Story to MT6_TestDirections.
Enums
We will be using enums to improve how the game processes directions.
Working Classes
We will be working with the following classes:
- Command - adventure.settings.Command
- CommandVerb - adventure.settings.CommandVerb
- GameController - adventure.settings.GameController
- GameInputProcessor - adventure.GameInputProcessor
Updating Code Logic
Sometimes we need to go in and change code for a variety of reasons. Today, you will be updating the logic that reads in commands to use an enum instead of strings.
CommandVerb is an enum that breaks down the different commands into variable names.
This has various advantages, one of which is enums provide autocomplete and fewer typos, where as Strings can be easily misspelled and could lead to runtime errorsLinks to an external site..
CommandVerb
Within CommandVerb, you'll find a list of predefined enum values and the static function getVerb.
Look over the list of commands. You'll then want to complete the getVerb method which turns a string into the appropriate command (the string should match the same spelling, ignoring case). Once a match is found, the appropriate CommandVerb should be returned. If no match is found, the function should return CommandVerb.INVALID.
Command
With CommandVerb ready to go, open the Command object and change each type of the variable verb from a String to CommandVerb.
For example,
String verb
now becomes
CommandVerb verb
Game Controller
With the Command object taking a CommandVerb instead of a String, go to GameController and find the method applyCommand(). It will be comparing the user's input with a static string (e.g. Command.HELP).
Create a switch statement to use the enum instead of comparing strings. If you have a command that will be used in later modules, just put break; as their logic.
GameInputProcessor
You will need to fix buildSimpleCommand and buildCommandWithObject to supply a CommandVerb instead of a string.
Testing
To run the tests for this assignment, run the following:
./gradlew test --tests com.adventure.MT6
or by right-clicking the MT6 file and selecting "Run 'MT6'"
You can check your code styling by running the linter with the following command:
./gradlew checkstyleMain
You can run the game by going to the Main class and clicking on the run icon to the left of the main() method.