[java] Java - Check if input is a positive integer, negative integer, natural number and so on.

Is there any in-built method in Java where you can find the user input's type whether it is positive, or negative and so on? The code below doesn't work. I am trying to find a way to input any in-built method that can do it at the if statement.

import java.util.Scanner;

public class Compare {

    public static void main(String[] args) { 

        Scanner input = new Scanner(System.in);

        System.out.print("Enter a number: ");
        int number = input.nextInt();

        if(number == int) 
            System.out.println("Number is natural and positive.");
    }
}

This question is related to java

The answer is


(You should you as Else-If statement to check the for the three different state (positive, negative, 0)

Here is a simple example (excludes the possibility of non-integer values)

  import java.util.Scanner;

  public class Compare {

   public static void main(String[] args) { 

    Scanner input = new Scanner(System.in);

    System.out.print("Enter a number: ");
    int number = input.nextInt();

    if( number == 0)
    { System.out.println("Number is equal to zero"); }
    else if (number > 0)
    { System.out.println("Number is positive"); }
    else 
    { System.out.println("Number is negative"); }


  }
 }

What about using the following:

int number = input.nextInt();
if (number < 0) {
    // negative
} else {
   // it's a positive
}

Use like below code.

if(number >=0 ) {
            System.out.println("Number is natural and positive.");
}

For integers you can use Integer.signum()

Returns the signum function of the specified int value. (The return value is -1 if the specified value is negative; 0 if the specified value is zero; and 1 if the specified value is positive.)


You could use if(number >= 0). The fact that you use int number = input.nextInt(); makes sure that it has to be an Integer.