Java-检查输入是否为正整数,负整数,自然数等. [英] Java - Check if input is a positive integer, negative integer, natural number and so on.
问题描述
Java中是否有任何内置方法,您可以在其中找到用户输入的类型,无论是正输入还是负输入等等?下面的代码不起作用.我试图找到一种方法来输入任何可以在if语句中执行的内置方法.
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.");
}
}
推荐答案
If you really have to avoid operators then use Math.signum()
返回参数的正则函数;如果参数为零零,如果自变量大于零,则为1.0,如果自变量大于-1.0,则为-1.0小于零.
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.
根据注释,这仅适用于double和float值.对于整数值,可以使用以下方法:
EDIT : As per the comments, this works for only double and float values. For integer values you can use the method:
这篇关于Java-检查输入是否为正整数,负整数,自然数等.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!