Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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.");     } } 
like image 413
kar Avatar asked Nov 04 '13 10:11

kar


People also ask

How do I make sure input is positive integer in Java?

Check Math.signum()Returns the signum function of the argument; zero if the argument is zero, 1.0 if the argument is greater than zero, -1.0 if the argument is less than zero.

How do you check if a number is negative or positive?

If a number is greater than zero, it is a positive number. If a number is less than zero, it is a negative number. If a number equals to zero, it is zero.


1 Answers

If you really have to avoid operators then use Math.signum()

Returns the signum function of the argument; zero if the argument is zero, 1.0 if the argument is greater than zero, -1.0 if the argument is less than zero.

EDIT : As per the comments, this works for only double and float values. For integer values you can use the method:

Integer.signum(int i)

like image 75
Juned Ahsan Avatar answered Sep 19 '22 15:09

Juned Ahsan