Anylogic中查找种群内匹配变量值的代理并获取其索引
问题背景
- 实现目标:查找存放于Main代理下、名为
dullieses的代理种群中目标代理的对应索引 - 匹配规则:遍历
dullieses种群内所有代理,匹配代理的int类型变量DullyID,找到变量值与int类型变量counter相等的目标代理 - 原有问题代码:
int i = 0; for ( i = 0; i < dullieses.size(); i++){ if (Main.dullieses(i).DullyID == counter){ traceln("I found myself! I have the index " + i); break; } }
- 运行报错信息:
Cannot make a static reference to the non-static method dullies(int) from type Main.
错误原因
- 静态调用非静态成员:
dullieses是Main代理实例的成员,不是Main类的静态成员,直接通过类名Main调用会触发静态引用非静态方法的报错。 - 集合取值语法错误:Java环境下List类型的代理种群,按下标获取元素需要调用
get(int index)方法,直接在集合对象后加圆括号传下标,会被编译器识别为调用同名方法,而非访问集合元素。
正确实现方案
根据代码编写位置分两种场景处理:
代码写在Main代理内部
直接通过当前Main实例访问种群即可,示例代码如下:
int targetIndex = -1; for (int i = 0; i < dullieses.size(); i++) { if (dullieses.get(i).DullyID == counter) { targetIndex = i; traceln("I found myself! I have the index " + i); break; } } // 未找到匹配代理的兜底逻辑 if (targetIndex == -1) { traceln("No matched agent found, please check DullyID value"); }
代码写在其他自定义代理内部
需要先获取当前运行环境的Main代理实例,再通过实例访问对应种群,以AnyLogic环境为例,可直接通过内置方法get_Main()获取Main实例,示例代码如下:
int targetIndex = -1; Main currentMain = get_Main(); for (int i = 0; i < currentMain.dullieses.size(); i++) { if (currentMain.dullieses.get(i).DullyID == counter) { targetIndex = i; traceln("I found myself! I have the index " + i); break; } } if (targetIndex == -1) { traceln("No matched agent found, please check DullyID value"); }
内容的提问来源于stack exchange,提问作者alyre
相关产品推荐
相关产品推荐

