创建未知数量的节点Java

时间:2013-05-02 21:21:24

标签: java nodes dijkstra

我正在开发一个程序,在一系列顶点上实现Dijkstra算法,并由用户输入边缘权重。在实际输入数据之前,我不知道用户将输入多少个顶点。 (第一个输入值之一将是顶点的总数)我的问题是我不知道如何为每个顶点创建一个节点而不需要硬编码,例如:

Vertex v1 = new Vertex("VERTEX INFO");
Vertex v2 = new Vertex("VERTEX INFO");
Vertex v3 = new Vertex("VERTEX INFO");

更具体地说,我的代码基于此示例here。在主方法中,此代码的顶点节点是硬编码的。

这是我在前一次尝试中获取用户输入时所写的内容(因为我遇到问题并且重新开始而被丢弃)

    ArrayList leftPoints = new ArrayList();
ArrayList rightPoints = new ArrayList();
ArrayList weights = new ArrayList();
    Scanner input = new Scanner(System.in);

String searchInput = input.nextLine();

    String[] searchCommand = searchInput.split(" ");
    for(int i = 0; i <searchCommand.length; i++){
        System.out.print(searchCommand[i] + " ");
    }

        searchInput = input.nextLine();
        int totalVertices = Integer.parseInt(searchInput);

        while (input.hasNextLine()){            
        searchInput = input.nextLine(); 
        searchCommand = searchInput.split(" ");             
        int x = Integer.parseInt(searchCommand[0]);
        int y = Integer.parseInt(searchCommand[1]);
        int weight = Integer.parseInt(searchCommand[2]);

        leftPoints.add(x);
        rightPoints.add(y);
        weights.add(weight);

        }

        int[] x = new int[leftPoints.size()];
        int[] y = new int[rightPoints.size()];
        int[] pathWeights = new int[weights.size()];

        for (int p = 0; p < x.length; p++){
            x[p] = ((Integer) leftPoints.get(p)).intValue();
            y[p] = ((Integer) rightPoints.get(p)).intValue();
            pathWeights[p] = ((Integer) weights.get(p)).intValue();
        }

我将arraylists转换为整数数组,尝试根本不起作用,但决定留下代码,以防它在这里帮助我

1 个答案:

答案 0 :(得分:0)

在用户输入顶点时创建顶点,并将它们添加到列表中。

Scanner sc = new Scanner(System.in);
List<Vertex> vertexList = new LinkedList<>();

while(sc.hasNext()) {
    vertexList.add(createVertexFromString(sc.next());
}

createVertexFromString显然是你自己写的一种方法。