Checking if a number is positive or negative using Java

A number is positive or negative using java :

 

In this article, we will create a java program to check whether the number entered by the user is positive or negative. The number is demonstrated as positive or negative by comparing the entered number with the Zero(0). If the number entered by the user is greater than zero, then the number is positive, else if the number is less than zero, then the number is negative and else the number is zero.

  • N > 0 then, number is Positive.
  • N < 0 then, number is Negative.
  • N = 0 then, number is Zero.
A number is positive or negative using java

Working :

Step 1 : Ask the user to enter a number.

Step 2 : Use first condition to check whether the number entered by the user is greater than zero or not. If the condition gets true, then the number is positive.

Step 3 : Now use second condition to check whether the number entered by the user is less than zero or not. If this condition gets true, then the number is negative.

Step 4 : And at last,  if no above condition gets true, then the number is equal to zero or can say that number is zero.

Step 5 : Print the result.

Code in Java :

//Java program to check a number is positive or negative
import java.util.Scanner;
public class pos_or_neg
{
public static void main(String[] args)
{
//scanner class declaration
Scanner sc = new Scanner(System.in);
//input from the user
System.out.print("Enter a Number : ");
int numb = sc.nextInt();
//condition for positive
if(numb > 0)
System.out.println("Positive");
//condition for negative
else if(numb < 0)
System.out.println("Negative");
else
System.out.println("Zero");
//closing scanner class(not compulsory, but good practice)
sc.close();
}
}

Output :

Enter a Number : 12

Positive


Enter a Number : -324

Negative


Enter a Number : 0

Zero

Please Login/Signup to comment