用户输入以显示最短路径

时间:2014-02-27 01:18:55

标签: java user-input indexoutofboundsexception breadth-first-search

我有一个ArrayOutOfBounds异常,我不知道为什么。我试图让用户输入他们希望程序从哪个城市开始,然后让我的程序从该点开始执行广度优先搜索。

我的课程将在一小时内完成,因此任何快速帮助都会很棒!

非常快,我的程序在邻接矩阵上执行广度优先搜索!

谢谢大家,这是我的主要内容:

       import java.util.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Collection;
import java.io.File;
import java.io.FileNotFoundException;

public class Main {


    public static void main(String[] args) 
    {



        //Lets create nodes 
        Node Seattle = new Node("Seattle");
        Node Vancouver=new Node("Vancouver");
        Node Portland = new Node("Portland");
        Node Houston = new Node("Houston");
        Node New_Orleans = new Node("New_Orleans");
        Node Miami = new Node("Miami");
        Node Omaha = new Node("Omaha");
        Node Louisville=new Node("Louisville");
        Node Boston = new Node("Boston");
        Node Boise = new Node("Boise ");
        Node Chicago = new Node("Chicago");
        Node Jacksonville = new Node("Jacksonville");
        Node Baltimore = new Node("Baltimore");
        Node Detroit = new Node("Detroit");
        Node Nashville =new Node("Nashville ");
        Node Oakland  = new Node("Oakland ");
        Node Denver= new Node("Denver ");
        Node Olympia = new Node("Olympia");
        Node Memphis = new Node("Memphis");

//
        //Create the graph, add nodes, create edges between nodes
        g.addNode(Seattle);
        g.addNode(Vancouver);
        g.addNode(Portland);
        g.addNode(Houston);
        g.addNode(New_Orleans);
        g.addNode(Miami);
        g.addNode(Omaha);
        g.addNode(Louisville);
        g.addNode(Boston);
        g.addNode(Boise);
        g.addNode(Chicago);
        g.addNode(Jacksonville);
        g.addNode(Baltimore);
        g.addNode(Detroit);
        g.addNode(Nashville);
        g.addNode(Oakland);
        g.addNode(Denver);
        g.addNode(Olympia);
        g.addNode(Memphis);

//      Scanner sc = new Scanner(System.in);
//      String shortPath = sc.next();
//      Node spath = new Node(shortPath);


        g.connectNode(Louisville,Memphis);

        g.connectNode(Houston,Seattle);

        g.connectNode(Boston,Vancouver);

        g.connectNode(Boise,Seattle);
        g.connectNode(Boise,Detroit);
        g.connectNode(Boise,Oakland);

        g.connectNode(Chicago,Olympia);

        g.connectNode(Portland,Seattle);

        g.connectNode(Jacksonville, Vancouver);

        g.connectNode(Baltimore, Vancouver);

        g.connectNode(Detroit, Boise);

        g.connectNode(Seattle, Portland );
        g.connectNode(Seattle, Houston );
        g.connectNode(Seattle, Vancouver);
        g.connectNode(Seattle, Denver);
        g.connectNode(Seattle, Boise);

        g.connectNode(Nashville, Memphis);

        g.connectNode(Oakland, Boise);
        g.connectNode(Oakland, Vancouver);

        g.connectNode(Vancouver, Seattle);
        g.connectNode(Vancouver,Olympia);
        g.connectNode(Vancouver,Jacksonville);
        g.connectNode(Vancouver,Baltimore);
        g.connectNode(Vancouver,Oakland);
        g.connectNode(Vancouver,Boston);

        g.connectNode(Denver, Seattle);

        g.connectNode(Olympia,Vancouver);
        g.connectNode(Olympia,Omaha);
        g.connectNode(Olympia,Chicago);

        g.connectNode(Memphis,Nashville);
        g.connectNode(Memphis,Louisville);
        g.connectNode(Memphis,Omaha);

        g.setRootNode(Houston);
        //Perform the traversal of the graph
        System.out.println("Shortest path is ------------->");
        g.bfs();
        ;
//      }
//      else {
//          throw new InvalidInputException();
//      }

        long lEndTime = System.currentTimeMillis(); 
        long difference = lEndTime - lStartTime;
        System.out.println("\nElapsed Time: " + difference + " ms");



    }

}

节点类:

public class Node 
{   


    public String label;
    public String label2;
    public boolean visited=false;
    //public Object equals;
    public Node(String name)
    {
        this.label= name;
//      this.label2 = name2;
    }
}

和我的图表类:

import java.io.FileNotFoundException;
import java.util.*;


public class Graph 
{
    //added
//  Vertex[] adjLists;

    public Node rootNode;
    public ArrayList nodes=new ArrayList();
    public int[][] adjMatrix;//Edges will be represented as adjacency Matrix
    int size;

    public void setRootNode(Node city)
    {
        this.rootNode=city;
    }

    public Node getRootNode()
    {
        return this.rootNode;
    }

    public void addNode(Node city)
    {
        nodes.add(city);
    }

    //This method will be called to make connect two nodes
    public void connectNode(Node start,Node end)
    {
        if(adjMatrix==null)
        {
            size=nodes.size();
            adjMatrix=new int[size][size];
        }

        int startIndex=nodes.indexOf(start);
        int endIndex=nodes.indexOf(end);
        adjMatrix[startIndex][endIndex]=1;      //initializing matrix with size 1 by 1
        adjMatrix[endIndex][startIndex]=1;
    }

    private Node getUnvisitedChildNode(Node n)
    {

        int index=nodes.indexOf(n);             //index is = to index of nodes
        int j=0;
        while(j<size)
        {
            if(adjMatrix[index][j]==1 && ((Node)nodes.get(j)).visited==false)
            {
                return (Node)nodes.get(j);
            }
            j++;
        }
        return null;
    }

    //BFS traversal of a tree is performed by the bfs() function
    public void bfs()
    {

        //BFS uses Queue data structure
        Queue q=new LinkedList();
        q.add(this.rootNode);
        printNode(this.rootNode);
        rootNode.visited=true;
        while(!q.isEmpty())
        {
            Node n=(Node)q.remove();
            Node child=null;
            while((child=getUnvisitedChildNode(n))!=null)
            {
                child.visited=true;
                printNode(child);
                q.add(child);
            }
        }
        //Clear visited property of nodes
        clearNodes();
    }


    //Utility methods for clearing visited property of node
    private void clearNodes()
    {
        int i=0;
        while(i<size)
        {
            Node n=(Node)nodes.get(i);
            n.visited=false;
            i++;
        }
    }

    //Utility methods for printing the node's label
    private void printNode(Node rootNode2)
    {
        System.out.print(rootNode2.label+" ---> ");
    }





}

1 个答案:

答案 0 :(得分:1)

似乎在Graph.getUnvisitedChildNode中,您使用nodes搜索nodes.indexOf(n)数组。首先在队列的第一个元素上完成,这是根节点,这一切都很好。

但是,根节点在new Node(shortPath)中设置为Main(第130行,请参阅编辑)。此新节点永远不会添加到阵列中。 Java不会查看此节点中的标签可能是什么,但目前只查看它是Node的相同实例。

您可以尝试通过向Node类添加以下方法来解决此问题:

@Override
public boolean equals(Object o) {
    if(o == null) return false;
    if(!(o instanceof Node)) return false;
    return label.equals(((Node)o).label);
}

如果标签相同,这个方法会说两个节点是相等的。我希望这会修复你的树。我会立即尝试这一点,同时你试着解释我的代码实际上做了什么。

编辑:你在这里修改了代码,它现在被注释掉并且在不同的行上。

EDIT2:对我来说,添加equals方法的覆盖似乎有效。