In this lab, you will learn how to use if
statements to make decisions in a Java program. The if
statement is one of the fundamental control flow structures in programming, allowing you to execute code conditionally based on specific conditions. You will write a program that takes user input and makes decisions using if
, else if
, and else
statements.
By the end of this lab, you will be able to:
if
statements in Java.if
, else if
, and else
to create decision-making logic.if
statements.cd ~
IfStatementExample.java
:nano IfStatementExample.java
import java.util.Scanner;
public class IfStatementExample {
public static void main(String[] args) {
// Create a Scanner object for input
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter their age
System.out.print("Enter your age: ");
int age = scanner.nextInt();
// If statement to check the age
if (age < 13) {
System.out.println("You are a child.");
} else if (age >= 13 && age < 18) {
System.out.println("You are a teenager.");
} else if (age >= 18 && age < 65) {
System.out.println("You are an adult.");
} else {
System.out.println("You are a senior.");
}
}
}
CTRL + O
, then hit Enter
to confirm the filename.CTRL + X
.javac
command:javac IfStatementExample.java
IfStatementExample.class
. Verify this by running:ls
java
command:java IfStatementExample
Enter your age: 25
You are an adult.
IfStatementExample.java
file again using Nano:nano IfStatementExample.java
if (age < 13) {
System.out.println("You are a child.");
} else if (age >= 13 && age < 18) {
System.out.println("You are a teenager.");
} else if (age == 18) {
System.out.println("You are exactly 18 years old.");
} else if (age > 18 && age < 65) {
System.out.println("You are an adult.");
} else {
System.out.println("You are a senior.");
}
System.out.print("Enter your favorite number: ");
int favoriteNumber = scanner.nextInt();
if (favoriteNumber == 7) {
System.out.println("7 is a lucky number!");
} else {
System.out.println("That's a nice number.");
}
.class
files:rm *.class
In this lab, you learned how to use if
statements to make decisions in a Java program. You wrote a program that uses if
, else if
, and else
statements to categorize users based on their age. You also practiced expanding the program by adding more conditions and inputs. Understanding control flow with conditional statements is crucial to creating dynamic and interactive Java programs.