主要方法中的Java代码与否?如果没有,我如何从main调用新方法?

时间:2014-04-16 09:55:35

标签: java main

我有以下Java类:

package openDIS;

import java.net.*;
import java.applet.*;
import java.awt.*;

import edu.nps.moves.disutil.*;
import edu.nps.moves.dis.*;

/*Receives PDUs from the network in IEEE format. */

public class EspduReceiver {

/*Max size of a PDU in binary format that can be received. Outdated- PDUs can be larger- but this is a reasonable starting point */
public static final int MAX_PDU_SIZE = 8192;

/*Retrieve PDU data for use by class methods */
MulticastSocket socket;
DatagramPacket packet;
InetAddress address;
PduFactory pduFactory = new PduFactory();


public static void main(String args[]){

    MulticastSocket socket;
    DatagramPacket packet;
    InetAddress address;
    PduFactory pduFactory = new PduFactory();

    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.  */
    }
} /*end main */

/*Create an 'Inner Class' (use as a C struct) to hold all of the variables pertaining to each PDU- each instance of the class
 * will hold a separate PDU. 
 * Create a method in Gui.java that will retrieve each instance of the inner class, and display the values on screen.*/

public class PDU{

    public String entityID;
    public double xLocation;
    public double yLocation;
    public double zLocation;
}



} /*end class */

当我运行课程时,它目前正在按照我的预期工作 - 并且我不断地向控制台打印消息,显示有关通过网络发送的PDU的信息,只要我让它保持运行

但是,我现在想要访问有关通过网络发送的消息的信息,该类正在读取并显示在控制台中,来自另一个类 - 我的Gui类,以便我可以将此信息提供给用户。

据我所知,为了让另一个类能够访问该类收集的信息,我需要在main方法之外定义一个方法,并将所有这些代码放入该方法中 - 与其他类一样无法访问另一个班级'主要方法?它是否正确?然后从我的main方法中调用new方法?

我通过从main方法中获取所有代码(如上所示)并将其放入以下方法中来完成此操作:public void receivePdu(){...}

然后我尝试使用行receivePdu()从我的main方法调用receivePdu();方法,但是我收到一条错误,上面写着"无法对非静态引用静态引用从类型EspduReceiver"开始的方法receivePdu(),并建议我更改' receivePdu()'的修饰符。到'静态'"。

如果我继续进行更改建议 - 在我的receivePdu()方法中打破代码,现在这是一种public static void方法,我会收到大量错误,例如&#34 ;不能对非静态字段套接字,地址,数据包,pduFactory"进行静态引用。

有没有人知道为什么我在我的主要方法中的receivePdu();电话上收到错误,以及我应该怎么做呢?

谢谢!

编辑16/04/2014 @ 11:35

如前所述,我已将主要方法中的所有代码移动到另一个名为receivePdu()的方法,现在我只是从主要方法调用该方法 - 我已在下面添加了更新的代码:

package openDIS;

import java.net.*;
import java.applet.*;
import java.awt.*;

import edu.nps.moves.disutil.*;
import edu.nps.moves.dis.*;

/*Receives PDUs from the network in IEEE format. */

public class EspduReceiver {

/*Max size of a PDU in binary format that can be received. Outdated- PDUs can be larger- but this is a reasonable starting point */
public static final int MAX_PDU_SIZE = 8192;

/*Retrieve PDU data for use by class methods */
MulticastSocket socket;
DatagramPacket packet;
InetAddress address;
PduFactory pduFactory = new PduFactory();

public 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.  */
    }
}

public static void main(String args[]){

    receivePdu();

} /*end main */

/*Create an 'Inner Class' (use as a C struct) to hold all of the variables pertaining to each PDU- each instance of the class
 * will hold a separate PDU. 
 * Create a method in Gui.java that will retrieve each instance of the inner class, and display the values on screen.*/

public class PDU{

    public String entityID;
    public double xLocation;
    public double yLocation;
    public double zLocation;
}



} /*end class */

我遇到的问题是我得到了错误"无法从类型EspduReceiver"中对非静态方法receivePdu()进行静态引用,但是,如果我按照Eclipse的建议,并更改' receivePdu()的修饰符;对于'静态',我得到了大量其他错误,因为没有别的东西是静态的。

我不希望任何东西是静态的,因为我需要从程序中的其他类引用此类中的方法。有什么建议可以解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

我相信你得到一个错误,因为你有两次声明的套接字,数据包,地址和pduFactory - 一次在main中,一次作为类的成员。而且你真的需要决定你是否希望receivePdu()是静态的。

你有几个决定: 1)socket,packet,address和pduFactory应该是receivePdu()的本地还是EspduReceiver的成员?如果对其本地接收到了对()"的答案,则需要删除这些变量的外部声明。如果答案是" EspduReceiver的成员"那么你需要删除内部声明,并可能参考每个使用" this.socket"使参考文献清楚。

2)与该决定交织在一起的是,如果这些变量应该是方法的本地变量,或者类的成员是否为receivePdu()是否为静态。

所以我认为有三种总体方法:

A)receivePdu()是一个静态成员,它只访问静态和局部变量(将实例变量转换为静态变量(如@barak所说)并删除局部变量。)

B)receivePdu()是在EspduReceiver实例上调用的方法,因此您需要实例化EspduReceiver的实例以便对其进行调用。 "插座"其他变量应该是成员,而不是在receivePdu()

中重新声明

C)将receivePdu()设置为单例类,并且类似于" B"。

祝你好运!

答案 1 :(得分:0)

你的一个课程中有一个主要方法是该课程的起点。分离gui,数据和逻辑是一种很好的做法。

所以在你的情况下我会做以下设计。

class Main - 包含以GUI或CMD模式启动的主要方法

class EspduReceiverGUI - 输入/输出的GUI类

class EspduReceiver - 实现接口EspduData

界面 EspduData - 定义了一种方法 getPDUData()

class PDU - 数据类对象

然后看起来像这样:

//Startpoint
public class Main
{
    public static void main(String[] args)
    {
         new EspduReceiverGUI();    //start gui somehow
    }
}

//GUI
public class EspduReceiverGUI
{
    //only exists once
    private static EspduData handler;

    //Get your Data and do something with it
    public EspduReceiverGUI()
    {
         handler = new EspduReceiver();
         PDU data = handler.getPDUData();

         doSomething(data);
    }
}

//Receiver
public class EspduReceiver implements EspduData
{
    //Variablen, Sockets etc.

    public PDU getPDUData()
    {
        //receive data and return
        //return pdu;
    }

}

除此之外,您还可以执行此操作,即Receiver类具有对GUI的引用,并在新数据到达时通知它。请参阅Observer Pattern