📌  相关文章
📜  Java中的 OptionalDouble getAsDouble() 方法及示例

📅  最后修改于: 2022-05-13 01:55:32.565000             🧑  作者: Mango

Java中的 OptionalDouble getAsDouble() 方法及示例

OptionalDouble帮助我们创建一个可能包含也可能不包含双精度值的对象。 getAsDouble()方法返回值 如果 OptionalDouble 对象中存在值,否则抛出NoSuchElementException

句法:

public double getAsDouble()

参数:此方法不接受任何内容。

返回值:此方法返回此 OptionalDouble 描述的值。

异常:如果不存在值,此方法将抛出NoSuchElementException

下面的程序说明了 getAsDouble() 方法:

方案一:

// Java program to demonstrate
// OptionalDouble.getAsDouble() method
  
import java.util.OptionalDouble;
  
public class GFG {
  
    public static void main(String[] args)
    {
  
        // Create an OptionalDouble instance
        OptionalDouble opDouble
            = OptionalDouble.of(44356.455);
  
        System.out.println("OptionalDouble: "
                           + opDouble.toString());
  
        // Get value in this instance
        // using getAsDouble()
        System.out.println("Value in OptionalDouble = "
                           + opDouble.getAsDouble());
    }
}
输出:
OptionalDouble: OptionalDouble[44356.455]
Value in OptionalDouble = 44356.455

方案二:

// Java program to demonstrate
// OptionalDouble.getAsDouble() method
  
import java.util.OptionalDouble;
  
public class GFG {
  
    public static void main(String[] args)
    {
  
        try {
  
            // Create an OptionalDouble instance
            OptionalDouble opDouble = OptionalDouble.empty();
  
            System.out.println("OptionalDouble: "
                               + opDouble.toString());
  
            // Get value in this instance
            // using getAsDouble()
            System.out.println("Value in OptionalDouble = "
                               + opDouble.getAsDouble());
        }
        catch (Exception e) {
  
            System.out.println("Exception: " + e);
        }
    }
}
输出:
OptionalDouble: OptionalDouble.empty
Exception: java.util.NoSuchElementException: No value present

参考资料: https: Java/util/OptionalDouble.html#getAsDouble()