You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java自定义Draw类isEmpty方法无法识别空状态且运行报错问题求助

问题原因分析

1. isEmpty方法逻辑错误

你实现的isEmpty方法永远会返回false,完全不符合预期:

public boolean isEmpty() {
    if (items.size() <= 0) {
        isEmpty = true;
    } return isEmpty = false;
}

不管items.size() <= 0的判断是否成立,最后一行都会执行isEmpty = false,并且把false作为方法返回值,所以哪怕盒子已经被抽空,调用isEmpty永远得到false。

2. 程序抛出错误的根本原因

当盒子元素抽完后,drawItem()方法会返回null:

  • 字符串盒子返回的null赋值给String类型的person是合法的,不会直接报错
  • 但整数盒子返回的Integer类型null,需要自动拆箱成基本类型int赋值给seat,这一步会触发NullPointerException,就是你遇到的运行时错误。
修复方案

第一步:修正isEmpty方法

直接基于集合的空状态返回即可,不需要额外维护冗余的成员变量:

public boolean isEmpty() {
    return items.isEmpty();
}

如果你要保留原有成员变量的设计,就调整返回逻辑:

public boolean isEmpty() {
    isEmpty = items.size() <= 0;
    return isEmpty;
}

第二步:添加空盒判断,避免报错同时打印提示

修改main方法中的循环逻辑,抽取元素前先判断盒子是否为空,空了就打印提示:

for (int index = 0; index < 10 ; index++) {
    // 抽取前先判断盒子是否已空
    if (myStringBox.isEmpty() || myIntegerBox.isEmpty()) {
        System.out.println("The box is empty");
        break;
    }
    String person = myStringBox.drawItem();
    int seat = myIntegerBox.drawItem();
            
    System.out.println(String.format("%s will occupy seat %s.", person, seat)); 
    boolean isEmpty = myStringBox.isEmpty();
    System.out.println("The box is empty: " + isEmpty);
            
    System.out.print("Enter 'd' to make draw. ('q' to stop)");
    code = scan.nextLine();
    if (code.equals("q")){
        System.out.println("you quit");
        break;
    }
} 

内容的提问来源于stack exchange,提问作者KLee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 18:15:11