Java Program to Determine Positive, Negative, or Zero Numbers

Respondido usando: GPT-4o-mini porJava Q&A Hub

Pergunta:

Introduce Java How To Find Positive or Negative Numbers and give examples

Resposta:

In Java, determining whether a number is positive, negative, or zero is a straightforward task that can be accomplished using simple conditional statements. A positive number is any number greater than zero, a negative number is any number less than zero, and zero itself is neither positive nor negative.

Basic Structure

To find out if a number is positive, negative, or zero, you can use the following structure:

  1. Input the number: You can take input from the user or define a number directly in the code.
  2. Use conditional statements: Use if, else if, and else statements to check the conditions.

Example Code

Here’s a simple Java program that demonstrates how to check if a number is positive, negative, or zero:

import java.util.Scanner;

public class NumberCheck {
    public static void main(String[] args) {
        // Create a Scanner object to read input
        Scanner scanner = new Scanner(System.in);
        
        // Prompt the user to enter a number
        System.out.print("Enter a number: ");
        double number = scanner.nextDouble(); // Read the number
        
        // Check if the number is positive, negative, or zero
        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.");
        }
        
        // Close the scanner
        scanner.close();
    }
}

Explanation of the Code

  1. Importing Scanner: The Scanner class is imported to read user input.
  2. Creating a Scanner Object: An instance of Scanner is created to read input from the console.
  3. Reading Input: The program prompts the user to enter a number and reads it using scanner.nextDouble().
  4. Conditional Statements:
    • The first if checks if the number is greater than zero (positive).
    • The else if checks if the number is less than zero (negative).
    • The else handles the case where the number is zero.
  5. Output: The program prints whether the number is positive, negative, or zero.
  6. Closing the Scanner: Finally, the scanner is closed to prevent resource leaks.

Example Outputs

  • If the user inputs 5, the output will be: The number is positive.
  • If the user inputs -3, the output will be: The number is negative.
  • If the user inputs 0, the output will be: The number is zero.

This simple program effectively demonstrates how to classify numbers in Java based on their value. You can expand this program further by adding more features, such as handling invalid input or allowing multiple checks in a loop.