Introduce Java How To Find Positive or Negative Numbers and give examples
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.
To find out if a number is positive, negative, or zero, you can use the following structure:
if
, else if
, and else
statements to check the conditions.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();
}
}
Scanner
class is imported to read user input.Scanner
is created to read input from the console.scanner.nextDouble()
.if
checks if the number is greater than zero (positive).else if
checks if the number is less than zero (negative).else
handles the case where the number is zero.5
, the output will be: The number is positive.
-3
, the output will be: The number is negative.
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.