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:
- Prompt the user to enter an integer.
- Use an
if-else
structure to determine whether the number is positive, negative, or zero.
- Implement a
switch
that assigns a category to the number based on its value (for example, "low," "medium," or "high").
- Display the results in the console using
System.out.println()
.
- 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.
View Example Code
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.