而循环Java将程序正在读取的PDU存储在ArrayList中
我有一个名为receivePdu()
的Java方法,它将侦听通过网络发送的任何PDU,并在控制台中打印实体ID和模拟中每个PDU的位置。
我正在使用一个while
循环来实现这一点,这样我的代码在运行的过程中就一直在监听pdu
现在我想修改我的代码,这样除了在控制台中打印关于每个单独PDU的信息外,它还将该信息存储在ArrayList中,以便我的程序中的另一个Java类可以使用它
我的receivePdu()
方法当前看起来如下所示:
public static void receivePdu(){
try{
/*Specify the socket to receive the data */
socket = new MulticastSocket(EspduSender.PORT);
address = InetAddress.getByName(EspduSender.DEFAULT_MULTICAST_GROUP);
socket.joinGroup(address);
/*Loop infinitely, receiving datagrams */
while(true){
byte buffer[] = new byte[MAX_PDU_SIZE];
packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
Pdu pdu = pduFactory.createPdu(packet.getData()); /* Commented on 15/04/2014 @ 09:15 */
if(pdu != null){
System.out.print("Got PDU of type: " + pdu.getClass().getName());
if(pdu instanceof EntityStatePdu){
EntityID eid = ((EntityStatePdu)pdu).getEntityID();
Vector3Double position = ((EntityStatePdu)pdu).getEntityLocation();
System.out.print(" EID:[" + eid.getSite() + ", " + eid.getApplication() + ", " + eid.getEntity() + "] ");
System.out.print(" Location in DIS coordinates: [" + position.getX() + ", " + position.getY() + ", " + position.getZ() + "]");
} else if(!(pdu instanceof EntityStatePdu)){
System.out.println("There are no PDUs currently being received.");
}
System.out.println();
}
} /*end while */
} /*end try */
catch(Exception e){
System.out.println(e);
e.printStackTrace();
System.out.println("This is where the error is being generated");
/*09/04/2014 @ 17:100
* If this exception gets called, presumably it either means that pdu is not an instance of EntityStatePdu, or
* that pdu does not actually hold a packet. */
}
}
现在,我已经在类中添加了一个ArrayList
(在receivePdu()
方法之外),使用行:public static ArrayList<pdu> espdu;
并修改了我的while循环,将每个PDU添加到ArrayList:
/*Loop infinitely, receiving datagrams */
while(true){
byte buffer[] = new byte[MAX_PDU_SIZE];
packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
Pdu pdu = pduFactory.createPdu(packet.getData()); /* Commented on 15/04/2014 @ 09:15 */
if(pdu != null){
System.out.print("Got PDU of type: " + pdu.getClass().getName());
if(pdu instanceof EntityStatePdu){
EntityID eid = ((EntityStatePdu)pdu).getEntityID();
Vector3Double position = ((EntityStatePdu)pdu).getEntityLocation();
System.out.print(" EID:[" + eid.getSite() + ", " + eid.getApplication() + ", " + eid.getEntity() + "] ");
System.out.print(" Location in DIS coordinates: [" + position.getX() + ", " + position.getY() + ", " + position.getZ() + "]");
espdu.add(pdu);
} else if(!(pdu instanceof EntityStatePdu)){
System.out.println("There are no PDUs currently being received.");
}
System.out.println();
}
} /*end while */
然而,当我现在运行我的代码时,尽管显示了接收到的第一个PDU,但我得到一个java.lang.NullPointerException
,其中调用了espdu.add(pdu);
行,它正在抱怨这一行:espdu.add(pdu);
我不明白为什么会出现空指针异常-有人有什么想法吗?我以上面提到的方式声明了ArrayList,其余变量位于类的顶部。在此方面的任何帮助或指导都将不胜感激
共 (0) 个答案