開始使用免費開始

偵測遺漏的數值

你想檢查咖啡店的銷售資料是否有遺漏值,例如銷售數量與金額。請透過檢查 null 來驗證一筆範例交易。

所需的套件(例如 ObjectsOptional)已替你匯入。

本練習屬於課程

使用 Java 進行資料清理

檢視課程

練習說明

  • 檢查銷售數量是否為 null。
  • 檢查銷售金額是否為 null。
  • 如果銷售數量為 null,將其設為預設值 1。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

public class CoffeeSalesExample {
    private record CoffeeSales(LocalDate date, String coffeeName,
            String paymentMethod, Integer quantity, Double amount) {
    }

    public static void main(String[] args) {
		CoffeeSales sale = new CoffeeSales(LocalDate.of(2024, 3, 1), "Latte", "cash", null, null);

		// Check if the sale quantity is null
        if (Objects.____(sale.____())) {
        	System.out.println("Missing quantity");
        }
    	
        // Check if the sale amount is null
        if (Objects.____(sale.____())) {
        	System.out.println("Missing amount");
        }
    	
        // Set a default value of 1 for sale quantity
        int defaultQuantity = Optional.____(sale.quantity()).____(1);
        System.out.println("Default quantity: " + defaultQuantity);
    }
}
編輯並執行程式碼