Conditionals (if, else, switch)

In this exercise, you'll learn how to use conditional statements in Java, which are essential for controlling the flow of program execution. Learn how to use if, else, and switch to make decisions based on different conditions. Through practical examples, you'll improve your ability to implement conditional logic in your programs and optimize the performance of your Java code.

Topic

Control Structures

Java Exercise

In this exercise, you will create a Java program that uses conditional structures such as if, else, and switch to make decisions based on user input. You will learn how to evaluate conditions and execute different blocks of code based on the entered values.

Instructions:

  1. Prompt the user to enter an integer.
  2. Use an if-else structure to determine whether the number is positive, negative, or zero.
  3. Implement a switch that assigns a category to the number based on its value (for example, "low," "medium," or "high").
  4. Display the results in the console using System.out.println().
  5. Compile and run the program to verify its operation.

This exercise will help you understand how to apply conditionals in Java to make decisions at runtime and improve the logic of your programs.


import java.util.Scanner;

public class ConditionalsJava {
    public static void main(String[] args) {
        // Create a Scanner object for user input
        Scanner scanner = new Scanner(System.in);
        
        // Ask the user to enter a number
        System.out.print("Enter an integer: ");
        int number = scanner.nextInt();

        // Determine if the number is positive, negative, or zero using if-else
        if (number > 0) {
            System.out.println("The number is positive.");
        } else if (number < 0) {
            System.out.println("The number is negative.");
        } else {
            System.out.println("The number is zero.");
        }

        // Evaluate the category of the number using switch
        switch (number) {
            case 1, 2, 3:
                System.out.println("Category: Low.");
                break;
            case 4, 5, 6:
                System.out.println("Category: Medium.");
                break;
            case 7, 8, 9:
                System.out.println("Category: High.");
                break;
            default:
                System.out.println("Category: Out of range (only 1-9).");
        }

        // Close the Scanner
        scanner.close();
    }
}

 Output:

Enter an integer: 5
The number is positive.
Category: Medium.

This program evaluates a user-entered number, determining whether it's positive, negative, or zero using if-else, and then assigns a category using switch. It's a great way to practice using conditional constructs in Java.


 Share this JAVA exercise