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

后端 未结 6 1123
长情又很酷
长情又很酷 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: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"); }
    
    
      }
     }
    

提交回复
热议问题