In this post, we are going to see how to find if the entered number is Positive or Negative, or Zero by writing a simple Java Program. The logic behind finding the entered number is Positive or Negative is so simple, let me just explain it.
If the number is greater than zero it is a Positive number else it is a Negative number, that’s it. So let us see how to achieve the same by writing a Java Program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import java.util.Scanner; /** * * @author gokiagur */ public class PostiveNegative { public static void main(String args[]) { int num; String result; Scanner in = new Scanner(System.in); //get the input from user System.out.print("Enter a positive or negative number: "); num = in.nextInt(); //check if the number is positive or negative or zero if (num > 0) { result = "Positive"; } else if (num == 0) { result = "Zero"; } else { result = "Negative"; } //print the result System.out.println("Entered number is: " + result); } } |
Sample output of the above program:
Positive number:
1 2 |
Enter a positive or negative number: 55 Entered number is: Positive |
Negative number:
1 2 3 |
Enter a positive or negative number: -95 Entered number is: Negative BUILD SUCCESSFUL (total time: 5 seconds) |
I hope the post is really helpful for you. Thanks for coming by.