这个JAVA代码是我自己写的。新人。目的是做一个并发的哈密圈寻路系统。但是有好多好多的Null pointer exception和小问题。求高手帮忙!!给大家磕头了!!
这是NODE的代码。import java.util.*;
/**
 * Title: Node.java
 * Description:  Every Node can do the same job as Worklist down.because this node just process there own solution, so the solution set is not necessary
 * 
 *
 * Copyright:    Copyright (c) 2001
 * Company:      Bond University
 * @author Chi Zhang
 * @version 1.0 25/10/01
 */class Node implements Runnable 
{
    protected Graph graph;
    protected Vector buffer=new Vector();
    protected String name;
    protected Set contents;    // Information stored at this node
    private volatile boolean stop;
    private Node dest[];
    private Vector sources;
    private Vector collection;
    private Path oldPath;
    private Warning[] allWarn=new Warning[10];
    private boolean askEnd = false;
    private Message[] messageCollection = new Message[10];
    private Iterator nodeIter = contents.iterator();
/**
     * * Constructors
 */
     public Node(String n, Set c)
     {
         name = n;
         contents = c;
        }
        public Node(String n)
        {
            name = n;
        }
/**
* some graphiv method;
*/
    public void setGraph(Graph g)
    { 
        graph = g;
        dest = g.getDestinations(this);
        for (int i = 0; i< dest.length;i++)
        {
            allWarn[i]= new Warning(dest[i]);
        }
        for (int i = 0; i< dest.length;i++)
        {
            messageCollection[i]= new Message(dest[i]);
        }
    }    public Node() { name = ""; }
    public String getName() { return name; }
    public Object getContents() { return contents; }
    public void setContents(Set o) { contents = o; }
    public boolean isEmpty() { return (contents == null); }
    public boolean equals(Node input){return ((input.getName()).equals(name));}
    public String toString() { return getName(); }
    public void getOn(){stop =true;}
/**
* it's the input buffer;
*/
    public Vector getBuffer(){return buffer;}
/**
* check the path is whether a HamiltonianCycle.
*/
    private boolean isHamiltonianCycle(Path p, Graph g) 
    {
        return ( p.hasCycle() && p.length() == g.size()+1 && p.first().equals(p.last()) );
     }
/**
* main method in the program. all program about the buffer control.
*/
    public void processBuffer() throws InterruptedException
    {
        Message a = (Message)buffer.get(0);
        if (a.getMission().equals(askEnd))//check whether this an end message
        {
            synchronized(this) 
            {
                buffer.remove(0);
                for (int i = 0;i<messageCollection.length;i++)
                {
                    if ((messageCollection[i].getSource()).equals(a.getSource()))//save the last receive message into every sender code.
                    {
                      messageCollection[i].setMission(a.getMission());
                    }
                }
                notify();  
            }// wake up the thread(s) waiting for the buffer to empty
        }
        else
        {
            synchronized(this) 
            {
                buffer.remove(0);
                notify();        // wake up the thread(s) waiting for the buffer to empty
            }
            Set ss = (Set)a.getMission();//get the input code.
            Node n = a.getSource();
            if (contents.contains(ss))//if this is already in the solution.
            {
                for (int i = 0;i<dest.length;i++)
                {
                    if (allWarn[i].getPosition()== n)//set the warning if receive an old solution.
                    {
                        allWarn[i].setAnswer(false);
                    }
                }
            }
            else
            {
                for (int i = 0;i<messageCollection.length;i++)//change the last receive message
                {
                    if ((messageCollection[i].getSource()).equals(a.getSource()))
                    {
                        messageCollection[i].setMission(a.getMission());
                    }
                }
                for (int i = 0;i<dest.length;i++)
                {
                    if (allWarn[i].getPosition()== n)
                    {
                        allWarn[i].setAnswer(true);
                    }
                }
                contents.addAll(ss);
                if (!contents.isEmpty())
                {
                    Set out = calcOutSet(this, ss);
                    contents = out;
                    for(int i= 0; i<dest.length;i++)
                    {
                        Message message = new Message(this, out);
                        dest[i].add(a);
                    }
                }
            }
        }
    }
    /**
     * check the solution and send this solution to every linked node.
     */
    private Set calcOutSet(Node n, Set in)
    {
        Set out = new HashSet();
        Iterator paths = in.iterator();
        while (paths.hasNext()) 
        {
            Path p = (Path) paths.next();
            if (!isHamiltonianCycle(p, graph)) 
            {
                // References to paths stored in sets.  Therefore need to make a new path object to
                // avoid unwanted changes through aliases
                p = new Path(p);
                p.add(n);
            }
            if (propagate(p)) 
            {
                out.add(p);
                oldPath = p;
            }
        }
        return (out);
    }
/**
 * check the path whether can be sperate.
 */
        private boolean propagate(Path p) 
        {
            return ((!oldPath.equals(p))&&(isHamiltonianCycle(p, graph) || !p.hasCycle())  );
        }
        public synchronized void add(Message p)
        { 
            buffer.add(p);
            notify();
        }
        /**
         * define how to run the each node.
         */
        public synchronized void run()
        {
            try
            {
                while(!stop)
                {
                    if(buffer.isEmpty()!=true)
                    {processBuffer();}
                    else 
                    for (int i = 0; i<dest.length;i++)
                    {
                        Message askStop = new Message(this,askEnd);
                        dest[i].add(askStop);
                    }
                    wait();
                }
            }catch(InterruptedException ie){return;}
        }
        /**
         * define how to finish.
         */
        public void finish()
        {
            synchronized(this)
            {
                while(checkEnd()!= true||(buffer.isEmpty()!= true)||(otherWarning()!=true))//only if receive no new information and input buffer 
                try{wait();}catch(InterruptedException ie){} //is empty and receive all and request
                stop = true;
                notify();
             }
         }
         /**
          * check whether recieve no new information
          */
         public boolean checkEnd()
         {
             for(int i = 0; i< allWarn.length; i++)
             {
                 if (allWarn[i].getAnswer()!=true){return  false;}
             }
                return true;
          }
          /**
           * send the end request
           */
          public boolean otherWarning()
          {
              for (int i=0;i<messageCollection.length;i++)
              {
                  if ((messageCollection[i].getMission()).equals(askEnd)!=true){return  false;}
                }
                return true;
            }
            /**
             * use to print
             */
            public String toResult() 
            {
                String s = "{";
                Iterator solIt =  nodeIter;
                while (solIt.hasNext())
                s += solIt.next() + ", ";
                return ( ((s.length() > 1) ? s.substring(0,s.length()-2) : s) + "}");
             }
      }
/**
 * build a class to tell others the warning;
 */
class Warning 
{
        protected Node position;
        protected boolean judge;
        /**
         * basic stucture.
         */
        public Warning(Node n) 
        {  
            position=n;
            judge = false;
        }
        public Warning(Node n, boolean b)
        {
            position = n;
            judge = b;
        }
        /**
         * basic method;
         */
  public Node getPosition() { return position; }
  public boolean getAnswer() { return judge; }
  public void setAnswer(boolean a){judge = a;}
}

解决方案 »

  1.   

    这个是我的主程序代码!!
    import java.util.*;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.Set;
    import java.util.Vector;/**
     * Title:        HamiltonSolver.java
     * Description:  use a Concurrency to make it work
     *
     * Copyright:    Copyright (c) 2001
     * Company:      Bond University
     * @author Chi Zhang
     * @version 1.0 26/10/01
     */
    /**
     * check Graph to get Nodes and Connections
     */
    public class HamiltonSolver 
    {
        public Graph graph;
        public Vector allNode;
        /**
         * main method
         */
          public void solve()
          {
              Graph graph = new Graph();
              String result = "";
              Node [] list = new Node[graph.size()];//get all node and save them into the input buffer.
              Iterator it = graph.nodesIterator();
              while(it.hasNext())
              { 
                int i = 0;
                list[i] = (Node)it.next();
                Node [] dests = graph.getDestinations(list[i]);
                for (int a = 0; a < dests.length; a++)
                {
                   Path startLine = new Path(dests[a]);
                   Message beginning = new Message(list[i],startLine);
                   list[i].add(beginning);
                }
              i++;
            }
           for (int count = 0; count<graph.size(); count++)//start the threads
           {
               new Thread(list[count]).start();
            }
            System.out.println(list[0].toResult());//print the result
      }
    }
      

  2.   

    这个是Message部分
    /**
     * this message just used to transfer information between nodes
     * 
     * @author (Chi Zhang) 
     * @version (2.0)
     */
    import java.util.*;
    public class Message
    {
    /**
     * the message mast have the set of path and the source node.
     */
        protected Node source;
        protected Object mission;
        public Message(Node o, Object n)
        {
            source = o;
            mission = n;
            
        }
        public Message(Node o)
        {
            source = o;
            mission = null;
        }
        /**
         * basic methods.
         */
        public Node getSource(){return source;}
        public Object getMission(){return mission;}
        public void setMission(Object ss){mission =ss;}
        /**
         * check two method whether is same.
         */
        public boolean equals(Message a)
        {
            if (source.equals(a.getSource())
            &&mission.equals(a.getMission()))
            {return true;}
            else return false;
        }}
      

  3.   

    这个是Pathimport java.util.Iterator;
    import java.util.Vector;
    import java.lang.Cloneable;/**
     * Title:        Path.java
     * Description:  Represents a path in a graph as a sequence of nodes
     *               I only increase a equals method
     * Copyright:    Copyright (c) 2001
     * Company:      Bond University
     * @author Chi Zhang
     * @version 1.0 25/10/01
     */public class Path {  /**
       * The nodes in the path are stored in a vector
       */
      protected Vector elements;  public Path() { elements = new Vector(); }
      public Path(Node n) { this(); this.add(n); }  /**
       * This constructor makes a new path have the same node sequence as another
       *
       * @param p the path to copy
       *
       */
      public Path(Path p) {
        this();
        Iterator it = p.elements.iterator();
        while (it.hasNext())
          elements.add(it.next());
      }
      /**
       * Add a node to the end of the path
       *
       * @param n the node to add
       */
      public void add(Node n) { elements.add(n); }
      /**
       * check two Path whether can be equals;
       */
      public boolean equals(Path p)
      {     
          Iterator it1 = p.elements.iterator();
          Iterator it2= elements.iterator();
          while (it1.hasNext()||it2.hasNext())
          {
              it1.next();
              it2.next();
              if(it1.equals(it2)!=true)
              return false;
            }
            return true;
        }
                  
      /**
       * Determine if the node is already in the path
       *
       * @param n the node being checked
       * @return  whether the node is in the path or not
       */
      public boolean contains(Node n) { return (elements.contains(n)); }  /**
       * Determine if the path contains a cycle
       *  - a path contains a cycle if the same node is in the path more than once
       *
       * @return  whether or not the path contains a cycle
       */
      public boolean hasCycle() {
        boolean cycle = false;
        Iterator it = elements.iterator();
        while (!cycle && it.hasNext()) {
          Object next = it.next();
          cycle = (elements.indexOf(next) != elements.lastIndexOf(next));
        }    return (cycle);
      }
      /**
       * Access the first and last nodes of the path
       *
       * @return first/last node in path
       */
      public Node first() { return ((Node) elements.firstElement()); }
      public Node last() { return ((Node) elements.lastElement()); }
      /**
       * Determine the length of the path
       *
       * @return the path length
       */
      public int length() { return (elements.size()); }
      public boolean isEmpty()
      {
          if (elements.size()==0) 
          return true;
          return false;
        }
            /**
       * String representation of a path is sequence of node names
       *
       * @return the string representation
       */
      public String toString() {
        Iterator it = elements.iterator();
        String s = "<";
        while (it.hasNext())
          s += ((Node) it.next()).getName() + ",";    return (  ((s.length() > 1) ? s.substring(0,s.length()-1) : s) + ">");
      }
    }
      

  4.   

    这 4 大层楼的代码估计没人会看的。空指针异常基本上是由于在编写代码时很不好编码习惯造成的。比如说从方法中传进来的参数,不检查是否为 null 就直接拿来使用了。
      

  5.   

    Graph这不知哪里的。Node.java有一堆东西没有import
      

  6.   

    public class NullPointerException
    extends RuntimeException
    当应用程序试图在需要对象的地方使用 null 时,抛出该异常。这种情况包括: 调用 null 对象的实例方法。 
    访问或修改 null 对象的字段。 
    将 null 作为一个数组,获得其长度。 
    将 null 作为一个数组,访问或修改其时间片。 
    将 null 作为 Throwable 值抛出。 
    应用程序应该抛出该类的实例,指示其他对 null 对象的非法使用。