1. Introduction
In this blog post, we will walk through a simple Java program that checks whether a given number is positive or negative. A number is positive if it is greater than zero and negative if it is less than zero.
2. Program Steps
1. Import the Scanner class from the java.util package for user input.
2. Define the main class named NumberChecker.
3. Inside the main class, define the main method.
4. Inside the main method, create an object of the Scanner class for user input.
5. Prompt the user to enter a number.
6. Check whether the entered number is positive, negative, or zero.
7. Print the result, indicating whether the number is positive, negative, or zero.
3. Code Program
import java.util.Scanner; // 1. Importing Scanner for user input
public class NumberChecker { // 2. Defining the main class
public static void main(String[] args) { // 3. Defining the main method
Scanner input = new Scanner(System.in); // 4. Creating Scanner object for user input
System.out.print("Enter a number: "); // 5. Prompting user to enter a number
double number = input.nextDouble(); // Receiving the number
if (number > 0) { // 6. Checking if the number is positive
System.out.println("The entered number is positive."); // 7. Printing result
} else if (number < 0) { // 6. Checking if the number is negative
System.out.println("The entered number is negative."); // 7. Printing result
} else { // 6. Checking if the number is zero
System.out.println("The entered number is zero."); // 7. Printing result
}
input.close(); // Closing the Scanner object to avoid memory leak
}
}
Output:
Enter a number: -5 The entered number is negative.
4. Step By Step Explanation
– Step 1: The Scanner class from the java.util package is imported to facilitate user input.
– Step 2: The main class named NumberChecker is defined.
– Step 3: The main method, which is the entry point of the program, is defined inside the main class.
– Step 4: A Scanner object named "input" is created to take user input.
– Step 5: The user is prompted to enter a number. For this example, the user enters -5.
– Step 6: The program then checks if the entered number is greater than, less than, or equal to zero, determining whether it is positive, negative, or zero, respectively.
– Step 7: Based on the condition met, the program prints out whether the entered number is positive, negative, or zero. In this case, since -5 is less than zero, the output is "The entered number is negative."
– Lastly, the Scanner object is closed to avoid any potential memory leak.