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

后端 未结 6 1085
长情又很酷
长情又很酷 2020-12-29 20:53

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 fi

相关标签:
6条回答
  • 2020-12-29 21:37

    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)

    0 讨论(0)
  • 2020-12-29 21:39

    What about using the following:

    int number = input.nextInt();
    if (number < 0) {
        // negative
    } else {
       // it's a positive
    }
    
    0 讨论(0)
  • 2020-12-29 21:39

    (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"); }
    
    
      }
     }
    
    0 讨论(0)
  • 2020-12-29 21:40

    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.)

    0 讨论(0)
  • 2020-12-29 21:43

    Use like below code.

    if(number >=0 ) {
                System.out.println("Number is natural and positive.");
    }
    
    0 讨论(0)
  • 2020-12-29 21:43

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

    0 讨论(0)
提交回复
热议问题