In this article, we will understand how to check whether a number is positive or negative. This is accomplished by checking if the given number is greater or less then 0.
Below is a demonstration of the same −
Input
Suppose our input is −
Enter the number: -3
Output
The desired output would be −
The number -30 is a negative number
Algorithm
Step 1 - START Step 2 - Declare an integer values namely my_input. Step 3 - Read the required values from the user/ define the values Step 4 - Using an if-else condition, check my_input > 0 value. Step 5 - If the result is true, then it’s a positive number, else it’s a negative number. Step 6 - Display the result Step 7 - Stop
Example 1
Here, the input is being entered by the user based on a prompt. You can try this example live in our coding ground tool
.
import java.util.Scanner;
public class PositiveNegative {
public static void main(String[] args) {
int my_input;
System.out.println("Required packages have been imported");
Scanner my_scanner = new Scanner(System.in);
System.out.println("A reader object has been defined ");
System.out.print("Enter the number : ");
my_input = my_scanner.nextInt();
if(my_input > 0)
System.out.println("The number " +my_input + " is a positive number");
else
System.out.println("The number " +my_input + " is a negative number");
}
}Output
Required packages have been imported A reader object has been defined Enter the number : -30 The number -30 is a negative number
Example 2
Here, the integer has been previously defined, and its value is accessed and displayed on the console.
public class PositiveNegative {
public static void main(String[] args) {
int my_input;
my_input = -30;
System.out.println("The number is defined as " +my_input);
if(my_input > 0)
System.out.println("The number " +my_input + " is a positive number");
else
System.out.println("The number " +my_input + " is a negative number");
}
}Output
The number is defined as -30 The number -30 is a negative number