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()
相關用法
- Java OptionalDouble equals()用法及代碼示例
- Java OptionalDouble toString()用法及代碼示例
- Java OptionalDouble orElseGet()用法及代碼示例
- Java OptionalDouble orElseThrow()用法及代碼示例
- Java OptionalDouble ifPresentOrElse()用法及代碼示例
- Java OptionalDouble stream()用法及代碼示例
- Java OptionalDouble hashCode()用法及代碼示例
- Java OptionalDouble of(double)用法及代碼示例
- Java OptionalDouble empty()用法及代碼示例
- Java OptionalDouble isPresent()用法及代碼示例
- Java OptionalDouble orElse(double)用法及代碼示例
- Java OptionalDouble ifPresent(DoubleConsumer)用法及代碼示例
- Java OptionalDouble orElseThrow(Supplier)用法及代碼示例
- Java Java.util.Collections.disjoint()用法及代碼示例
- Java Java lang.Long.byteValue()用法及代碼示例
注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 OptionalDouble getAsDouble() method in Java with examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。