Java Program to Check if a Number is Positive or Negative

1. Introduction

Determining if a number is positive or negative is a basic programming task that introduces conditional statements. This functionality can be useful in various applications, such as data validation or mathematical computations. In this blog post, we will write a simple Java program that checks if a given number is positive or negative.

2. Program Steps

1. Import the Scanner class to read user input.

2. Prompt the user to enter a number.

3. Use an if-else statement to check if the number is positive, negative, or zero.

4. Display the result.

5. Close the Scanner object to prevent resource leaks.

3. Code Program

import java.util.Scanner;

public class CheckNumberSign {
    public static void main(String[] args) {
        // Creating a Scanner object to read input from the user
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter a number:");
        double number = scanner.nextDouble(); // Reading the number

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

        scanner.close(); // Closing the scanner
    }
}

Output:

Enter a number:
-5
-5 is a negative number.

Explanation:

1. The program begins by importing the Scanner class, which is used to obtain input from the user.

2. It then prompts the user to enter a number. This input is read and stored in a variable called number.

3. An if-else statement checks the value of number. If the value is greater than zero, it means the number is positive, and a corresponding message is displayed. If the value is less than zero, the number is negative, and a different message is shown. If the number is exactly zero, a specific message indicating that the number is zero is displayed.

4. This approach uses simple conditional logic to classify the number into positive, negative, or zero.

5. Finally, the Scanner object is closed to prevent resource leaks, which is a best practice for handling user input in Java.

Comments