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

AnyLogic循环事件通过Enter Block添加Agent触发空指针异常求助

解决循环事件创建Agent时的NullPointerException问题

问题场景

通过循环事件从scans数据库读取参数,创建指定数量的Ressource Agent(未使用Exit Block)。首次运行正常,但后续触发NullPointerException,代码如下:

parameter = (int) selectFrom(scans)
    .where(scans.al_id.gt(id))
    .firstResult(scans.scans);
    
for(int i=0; i<parameter; i++){
    Ressource ressource = new Ressource ();
    enter.take(ressource); 
};

id++;

问题原因

当scans表中没有符合scans.al_id.gt(id)条件的记录时,firstResult(scans.scans)会返回null,直接将null强转为int会抛出NullPointerException。首次运行时有匹配数据所以正常,后续id递增后无匹配记录,就触发了错误。

解决方法

  1. 先判断查询结果是否为null,再赋值参数
    修改查询逻辑,避免直接强转空值:
Integer queryResult = (Integer) selectFrom(scans)
    .where(scans.al_id.gt(id))
    .firstResult(scans.scans);

// 无匹配记录时将参数设为0
parameter = queryResult != null ? queryResult : 0;

for(int i=0; i<parameter; i++){
    Ressource ressource = new Ressource();
    enter.take(ressource); 
};

id++;
  1. 可选优化:跳过无意义的循环
    如果参数为0,直接跳过循环,减少不必要的执行:
Integer queryResult = (Integer) selectFrom(scans)
    .where(scans.al_id.gt(id))
    .firstResult(scans.scans);

parameter = queryResult != null ? queryResult : 0;

if(parameter > 0){
    for(int i=0; i<parameter; i++){
        Ressource ressource = new Ressource();
        enter.take(ressource); 
    }
}

id++;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 15:03:25