Back

Activity 2.2 If Statements

divider

Introduction

Activity 2.2

If Statements

Topics

  • Making Decisions
  • If Statements
  • Common Mistakes when Writing If Statements

Making Decisions

Programs often need to make choices. As discussed in the previous lesson, a program often needs to decide what to do based on certain circumstances.

This kind of decision-making is called selection. It lets your program follow different paths depending on what's true.

The if Statement

An if statement allows your program to check a condition and decide whether or not to execute a block of code based on whether its condition is true or false.

System.out.print("Enter your age: ");
int age = input.nextInt();
if (age >= 16) {
System.out.println("You can drive!");
}

Components of an if Statement

if (age >= 16) {
System.out.println("You can drive!");
}

1. (if) If keyword - Denotes the beginning of an if statement.

2. (age >= 16) Condition - A boolean expression that evaluates true or false.

3. ({ }) Code Block: A group of statements surrounded by braces.

Demo: Create the Driving Age Checker

System.out.print("Enter your age: ");
int age = input.nextInt();
if (age >= 16) {
System.out.println("You can drive!");
}
Sample Output 1
Enter your age: 17 [Enter]
You can drive!
Sample Output 2
Enter your age: 12 [Enter]
[No output]

Common Mistakes

1. Forgetting to Close a Code Block: Always let your editor generate the closing brace and avoid deleting it. New programmers often forget to close their code blocks.

2. Poor indentation: Indent all code within a block by one tab. While not required by the compiler, this makes your code much easier to read and maintain.

3. Unnecessary semi-colons: if (condition); { Avoid placing semi-colons after an if statement's condition. A semi-colon here separates the condition from the code block, causing the block to run unconditionally.

Key Terms

Selection
The ability of a program to choose which code to execute based on a condition.
if Statement
A fundamental control flow structure that allows a program to execute a block of code only if a specified condition is true. It consists of the if keyword, a condition, and a code block.

Key Terms

Condition
A logical expression that evaluates to a Boolean value (true or false). It determines whether the code inside an if statement's code block will be executed.
Code Block
A group of one or more programming statements enclosed in curly braces ({ }). In an if statement, this block of code is executed when the condition is met.

'F' → Fullscreen

Objectives

  • icon Constructing If Statements
  • icon Evaluating Conditions
  • icon Grouping code into code blocks
divider

Activity Tasks

  • icon Create a new project named 2-2-If-Statements.
  • icon Complete each task individually.

Task 1: Age Validator

Program.java
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("--- Demo 1 - Age Validator ---");
System.out.print("Enter your age: ");
int userAge = input.nextInt();
input.nextLine(); // Consume newline
if (userAge >= 16) {
System.out.println("Time to hit the road! You've earned your driving permit.\n");
}
if (userAge >= 18) {
System.out.println("Adulting 101: You can now vote and live independently.");
System.out.println("Please exit your mom's basement.\n");
}
if (userAge >= 35) {
System.out.println("You're old enough to run for president.");
System.out.print("Enter your full name: ");
String fullName = input.nextLine();
System.out.print("What year will you run? ");
String electionYear = input.nextLine();
System.out.print("What's your nickname (e.g., 'The Awesome')? ");
String nickName = input.nextLine();
System.out.println(nickName + " " + fullName + " for president in " + electionYear + "!");
}
System.out.println("Press enter to continue...");
input.nextLine();
// -----------------------------------------------------------------------------
//
}
}

Task 2: Simple Score Calculator

Program.java
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
36 collapsed lines
Scanner input = new Scanner(System.in);
System.out.println("--- Demo 1 - Age Validator ---");
System.out.print("Enter your age: ");
int userAge = input.nextInt();
input.nextLine(); // Consume newline
if (userAge >= 16) {
System.out.println("Time to hit the road! You've earned your driving permit.\n");
}
if (userAge >= 18) {
System.out.println("Adulting 101: You can now vote and live independently.");
System.out.println("Please exit your mom's basement.\n");
}
if (userAge >= 35) {
System.out.println("You're old enough to run for president.");
System.out.print("Enter your full name: ");
String fullName = input.nextLine();
System.out.print("What year will you run? ");
String electionYear = input.nextLine();
System.out.print("What's your nickname (e.g., 'The Awesome')? ");
String nickName = input.nextLine();
System.out.println(nickName + " " + fullName + " for president in " + electionYear + "!");
}
System.out.println("Press enter to continue...");
input.nextLine();
// -----------------------------------------------------------------------------
System.out.println("\n--- Demo 2 - Simple Score Calculator ---");
System.out.print("Enter your score (0-100): ");
int score = input.nextInt();
input.nextLine(); // Consume newline
if (score >= 60) {
System.out.println("You passed!");
}
if (score < 60) {
System.out.println("You did not pass. Keep studying!");
}
System.out.println("Press enter to continue...");
input.nextLine();
// -----------------------------------------------------------------------------
//
}
}

Task 3: Temperature Check

Program.java
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
55 collapsed lines
Scanner input = new Scanner(System.in);
System.out.println("--- Demo 1 - Age Validator ---");
System.out.print("Enter your age: ");
int userAge = input.nextInt();
input.nextLine(); // Consume newline
if (userAge >= 16) {
System.out.println("Time to hit the road! You've earned your driving permit.\n");
}
if (userAge >= 18) {
System.out.println("Adulting 101: You can now vote and live independently.");
System.out.println("Please exit your mom's basement.\n");
}
if (userAge >= 35) {
System.out.println("You're old enough to run for president.");
System.out.print("Enter your full name: ");
String fullName = input.nextLine();
System.out.print("What year will you run? ");
String electionYear = input.nextLine();
System.out.print("What's your nickname (e.g., 'The Awesome')? ");
String nickName = input.nextLine();
System.out.println(nickName + " " + fullName + " for president in " + electionYear + "!");
}
System.out.println("Press enter to continue...");
input.nextLine();
// -----------------------------------------------------------------------------
System.out.println("\n--- Demo 2 - Simple Score Calculator ---");
System.out.print("Enter your score (0-100): ");
int score = input.nextInt();
input.nextLine(); // Consume newline
if (score >= 60) {
System.out.println("You passed!");
}
if (score < 60) {
System.out.println("You did not pass. Keep studying!");
}
System.out.println("Press enter to continue...");
input.nextLine();
// -----------------------------------------------------------------------------
System.out.println("\n--- Demo 3 - Temperature Check ---");
System.out.print("What is the current temperature in Fahrenheit? ");
int currentTemp = input.nextInt();
input.nextLine(); // Consume newline
if (currentTemp <= 32) {
System.out.println("Brrr! It's freezing. Don't forget your coat!");
}
if (currentTemp > 32 && currentTemp <= 65) {
System.out.println("It's a bit chilly. A light jacket should be perfect.");
}
if (currentTemp > 65) {
System.out.println("It's warm outside. Enjoy the nice weather!");
}
System.out.println("Press enter to continue...");
input.nextLine();
// -----------------------------------------------------------------------------
//
}
}

Task 4: Letter Grade Calculator

Program.java
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
78 collapsed lines
Scanner input = new Scanner(System.in);
System.out.println("--- Demo 1 - Age Validator ---");
System.out.print("Enter your age: ");
int userAge = input.nextInt();
input.nextLine(); // Consume newline
if (userAge >= 16) {
System.out.println("Time to hit the road! You've earned your driving permit.\n");
}
if (userAge >= 18) {
System.out.println("Adulting 101: You can now vote and live independently.");
System.out.println("Please exit your mom's basement.\n");
}
if (userAge >= 35) {
System.out.println("You're old enough to run for president.");
System.out.print("Enter your full name: ");
String fullName = input.nextLine();
System.out.print("What year will you run? ");
String electionYear = input.nextLine();
System.out.print("What's your nickname (e.g., 'The Awesome')? ");
String nickName = input.nextLine();
System.out.println(nickName + " " + fullName + " for president in " + electionYear + "!");
}
System.out.println("Press enter to continue...");
input.nextLine();
// -----------------------------------------------------------------------------
System.out.println("\n--- Demo 2 - Simple Score Calculator ---");
System.out.print("Enter your score (0-100): ");
int score = input.nextInt();
input.nextLine(); // Consume newline
if (score >= 60) {
System.out.println("You passed!");
}
if (score < 60) {
System.out.println("You did not pass. Keep studying!");
}
System.out.println("Press enter to continue...");
input.nextLine();
// -----------------------------------------------------------------------------
System.out.println("\n--- Demo 3 - Temperature Check ---");
System.out.print("What is the current temperature in Fahrenheit? ");
int currentTemp = input.nextInt();
input.nextLine(); // Consume newline
if (currentTemp <= 32) {
System.out.println("Brrr! It's freezing. Don't forget your coat!");
}
if (currentTemp > 32 && currentTemp <= 65) {
System.out.println("It's a bit chilly. A light jacket should be perfect.");
}
if (currentTemp > 65) {
System.out.println("It's warm outside. Enjoy the nice weather!");
}
System.out.println("Press enter to continue...");
input.nextLine();
// -----------------------------------------------------------------------------
System.out.println("\n--- Demo 4 - Letter Grade Calculator ---");
System.out.print("Enter your final grade percentage (0-100): ");
int finalGrade = input.nextInt();
if (finalGrade >= 90) {
System.out.println("You got an A! Excellent work!");
}
if (finalGrade >= 80 && finalGrade < 90) {
System.out.println("You got a B! Great job!");
}
if (finalGrade >= 70 && finalGrade < 80) {
System.out.println("You got a C. Solid effort.");
}
if (finalGrade >= 60 && finalGrade < 70) {
System.out.println("You got a D. You passed, but there's room to improve.");
}
if (finalGrade < 60) {
System.out.println("You got an F. Let's review the material and try again.");
}
//
}
}
divider

Sample Output

Your program output should something similar to the sample output below.

Sample Output
--- Demo 1 - Age Validator ---
Enter your age: 35
Time to hit the road! You've earned your driving permit.
Adulting 101: You can now vote and live independently.
Please exit your mom's basement.
You're old enough to run for president.
Enter your full name: Anthony Mortimer
What year will you run? 2028
What's your nickname (e.g., 'The Awesome')? Sleepy
Sleepy Anthony Mortimer for president in 2028!
Press enter to continue...
--- Demo 2 - Simple Score Calculator ---
Enter your score (0-100): 83
You passed!
Press enter to continue...
--- Demo 3 - Temperature Check ---
What is the current temperature in Fahrenheit? 72
It's warm outside. Enjoy the nice weather!
Press enter to continue...
--- Demo 4 - Letter Grade Calculator ---
Enter your final grade percentage (0-100): 76
You got a C. Solid effort.
divider

Reflection Questions

You may write your reflection answers as comments at the bottom of your code.

  1. Describe a real-life situation where you make a decision based on multiple conditions. How would you translate that decision-making process into an if statement using logical operators like && (AND) and || (OR)?
divider

Submission

Submit your activity and reflection answers to the appropriate dropbox.

Activity Complete