当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java OptionalDouble getAsDouble()用法及代码示例


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

用法:

public double getAsDouble()

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


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

异常:如果不存在任何值,则此方法将引发NoSuchElementException

以下示例程序旨在说明getAsDouble()方法:

示例1:

// 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

示例2:

// 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://docs.oracle.com/javase/10/docs/api/java/util/OptionalDouble.html#getAsDouble()



相关用法


注:本文由纯净天空筛选整理自AmanSingh2210大神的英文原创作品 OptionalDouble getAsDouble() method in Java with examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。