判断一个数字是否是 Java 中的 Double

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1641619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 18:08:15  来源:igfitidea点击:

Figuring out whether a number is a Double in Java

javatypeof

提问by

I'm a Java newbie. I'm trying to figure out whether a number is a Double with something like this:

我是 Java 新手。我试图弄清楚一个数字是否是一个像这样的 Double :

if ( typeof ( items.elementAt(1) )== Double ) {
       sum.add( i, items.elementAt(1));
}

Would appreciate if someone could tell me how to rearrange the syntax to make this work properly.

如果有人能告诉我如何重新排列语法以使其正常工作,我将不胜感激。

采纳答案by ski

Try this:

尝试这个:

if (items.elementAt(1) instanceof Double) {
   sum.add( i, items.elementAt(1));
}

回答by Chookoos

Reflection is slower, but works for a situation when you want to know whether that is of type Dog or a Cat and not an instance of Animal. So you'd do something like:

反射较慢,但适用于您想知道它是 Dog 还是 Cat 类型而不是 Animal 实例的情况。所以你会做这样的事情:

if(null != items.elementAt(1) && items.elementAt(1).getClass().toString().equals("Cat"))
{
//do whatever with cat.. not any other instance of animal.. eg. hideClaws();
}

Not saying the answer above does not work, except the null checking part is necessary.

不是说上面的答案不起作用,除了空检查部分是必要的。

Another way to answer that is use generics and you are guaranteed to have Double as any element of items.

回答这个问题的另一种方法是使用泛型,您可以保证将 Double 作为项目的任何元素。

List<Double> items = new ArrayList<Double>();

回答by kumaranc

Use regular expression to achieve this task. Please refer the below code.

使用正则表达式来完成这个任务。请参考以下代码。

public static void main(String[] args) {
    try {

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter your content: ");
        String data = reader.readLine();            
        boolean b1 = Pattern.matches("^\d+$", data);
        boolean b2 = Pattern.matches("[0-9a-zA-Z([+-]?\d*\.+\d*)]*", data); 
        boolean b3 = Pattern.matches("^([+-]?\d*\.+\d*)$", data);
        if(b1) {
            System.out.println("It is integer.");
        } else if(b2) {
            System.out.println("It is String. ");
        } else if(b3) {
            System.out.println("It is Float. ");
        }           
    } catch (IOException ex) {
        Logger.getLogger(TypeOF.class.getName()).log(Level.SEVERE, null, ex);
    }
}

回答by Rob Fox

Since this is the first question from Google I'll add the JavaScript style typeofalternative here as well:

由于这是来自 Google 的第一个问题,因此我还将在typeof此处添加 JavaScript 样式替代方案:

myObject.getClass().getName() // String