Java Double isNaN()方法及示例

来源:这里教程网 时间:2026-02-17 20:52:51 作者:

Java Double isNaN()方法及示例

Java中Double类的 isNaN() 方法是一个内置的方法,如果这个Double值或指定的Double值是Not-a-Number(NaN),则返回真,否则返回假。

语法:

public boolean isNaN()        orpublic static boolean isNaN(double val)

参数 :该函数接受一个单一的参数 val ,当以静态方法的形式直接调用Double类时,该参数指定要检查的值。当该方法作为实例方法使用时,不需要该参数。

返回值 :如果val是NaN,它返回 true ,否则返回 false

以下程序说明了Java中的isNaN()方法。

程序1 :

// Java code to demonstrate// Double isNaN() method// without parameter  class GFG {    public static void main(String[] args)    {          // first example        Double f1 = new Double(1.0 / 0.0);          boolean res = f1.isNaN();          // printing the output        if (res)            System.out.println(f1 + " is NaN");        else            System.out.println(f1 + " is not NaN");          // second example        f1 = new Double(0.0 / 0.0);          res = f1.isNaN();          // printing the output        if (res)            System.out.println(f1 + " is NaN");        else            System.out.println(f1 + " is not NaN");    }}

输出。

Infinity is not NaNNaN is NaN

程序2

// Java code to demonstrate// Double isNaN() method// with parameter  class GFG {    public static void main(String[] args)    {          // first example        Double f1 = new Double(1.0 / 0.0);          boolean res = f1.isNaN(f1);          // printing the output        if (res)            System.out.println(f1 + " is NaN");        else            System.out.println(f1 + " is not NaN");          // second example        f1 = new Double(0.0 / 0.0);          res = f1.isNaN(f1);          // printing the output        if (res)            System.out.println(f1 + " is NaN");        else            System.out.println(f1 + " is not NaN");    }}

输出。

Infinity is not NaNNaN is NaN

参考资料: https://docs.oracle.com/javase/7/docs/api/java/lang/Float.html#isNaN()

相关推荐