Pages

Monday, February 10, 2020

Java Program to Check Whether a Number is Positive or Negative

1. Introduction


In this programming tutorial, We will learn how to check the given number is a positive or negative value. This can be done using if else condition and with '<', '>' operators.

If-else Statement in java examples.

Java Program to Check Whether a Number is Positive or Negative




2. Example Program To Check if a Number is Positive or Negative using if-else

Following is a simple example using if and else statements.

package com.javaprogramto.w3schools.engineering.programs;

import java.util.Scanner;

/**
 * 
 * Java Program to Check Whether a Number is Positive or Negative
 * 
 * @author JavaProgramTo.com
 */
public class CheckNumberPositiveNegative {

    public static void main(String[] args) {
    
        System.out.println("Enter a int value : ");
        Scanner s = new Scanner(System.in);
        int intValue = s.nextInt();
        
        if(intValue > 0 ) {
            System.out.println(intValue+" is a positive number");
        } else if(intValue < 0){
            System.out.println(intValue+" is a negative number");
        } else {
            System.out.println(intValue+" is not a positive or negative number");
        }
        
        System.out.println("Enter a double value : ");
        double doubleValue = s.nextDouble();
        
        if(doubleValue > 0 ) {
            System.out.println(doubleValue+" is a positive number");
        } else if(doubleValue < 0){
            System.out.println(doubleValue+" is a negative number");
        } else {
            System.out.println(doubleValue+" is not a positive or negative number");
        }

    }

}

Output:

Enter a int value : 100
100 is a positive number
Enter a double value : -100.09
-100.09 is a negative number

In this program, we are checking positive or negative for int and double values. If condition expression is true then it is positive value else checking for negative value and the final else means the number is 0.

3. Possible Exceptions


If an invalid number is given like "-12-.23" then will get the run time exception saying InputMismatchException.


Enter a int value : 15
15 is a positive number
Enter a double value : -12-.23
Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:864)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextDouble(Scanner.java:2413)
    at com.javaprogramto.w3schools.engineering.programs.CheckNumberPositiveNegative.main(CheckNumberPositiveNegative.java:28)


Adding two numbers in java
Adding three numbers

4. Conclusion


In this article, We have seen how to check the given int or double value is a positive or negative number using the if-else statement.


No comments:

Post a Comment

Please do not add any spam links in the comments section.