开始使用免费开始使用

检测缺失数值

您想检查咖啡店的销售数据是否存在缺失值,例如销售数量和销售金额。请通过空值检查来验证一条示例销售记录。

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);
    }
}
编辑并运行代码