读取顶点和创建边



对于这个任务,我应该创建一个"想要的"网络,应该是一个图。您读取的第一个文件包含一个文本文件,其中包含顶点from/to和一些其他数据。我也有一个内部计数器,用来计算addVertex被使用了多少次。到目前为止,它是正确的,测试打印是正确的,但是当我运行它在列表中没有顶点,即使它说它已经被添加。知道为什么我不把它添加到列表中吗?

我是这样读的:

static Graph graph;
private static void createNetwork(String fil1) {
    try {
        Scanner sc = new Scanner(new File(fil1));
        graph = new Graph();
        while (sc.hasNextLine()) {
            String line = sc.nextLine();
            String[] split = line.split("t");
            int[] connections = new int[split.length];
            //  System.out.println(line); // test utskrift
            for (int i = 0; i < split.length; i++) {
                connections[i] = Integer.parseInt(split[i].trim());
            }
            graph.addVertex(connections);
        }
    } catch (Exception e) {
    }
}

和其他一些被调用的方法:

public void addVertex(int[] cons) {//, int tid, int ore) {
    if (cons == null) {
        return;
    }
    boolean added = false;
    Vertex fra, til;
    int tid = cons[2];
    int ore = cons[3];
    fra = new Vertex(cons[0], cons[1], cons[2], cons[3]);
    til = new Vertex(cons[1], cons[0], cons[2], cons[3]);
    if (verticies.contains(fra) == false) { //, tid, ore)
        System.out.println(
                fra.id + " --> " + til.id + " Ble lagt til i lista! " + size);
        size++;
        added = verticies.add(fra); //, tid, ore
        //   addEdge(fra, til, tid, ore);
        //  addEdge(til, fra, tid, ore);
        // addBiEdges(fra, til, tid, ore);
        //  return true;
    }
}
public boolean addBiEdges(Vertex fra, Vertex til, int tid, int ore) throws IllegalArgumentException {
    return false; // addEdge(fra, til, tid, ore) && addEdge(til, fra, tid, ore);
}
public void addEdge(Vertex fra, Vertex til, int tid, int ore) throws IllegalArgumentException {
    if (verticies.contains(fra) == false)
        throw new IllegalArgumentException(fra.id + " er ikke med i grafen!");
    if (verticies.contains(til) == false)
        throw new IllegalArgumentException(til.id + " er ikke med i grafen!");
    Edge e = new Edge(fra, til, tid, ore);
    if (fra.findEdge(til) != null) {
        return;
    } else {
        fra.addEdges(e);
        til.addEdges(e);
        edges.add(e);
        // return true;
    }
}

class Graph {
    public static int size;
    HashMap<Integer, Vertex> graph;
    protected List<Vertex> verticies;
    protected List<Edge> edges;
    // Brukes til Dijkstras algoritmen
    public List<Vertex> kjent;
    public List<Vertex> ukjent;

    public Graph() {
        graph = new HashMap<Integer, Vertex>();
        kjent = new ArrayList<Vertex>();
        ukjent = new ArrayList<Vertex>();
        verticies = new ArrayList<Vertex>();
        edges = new ArrayList<Edge>();
    }
}

它们一开始就没有被添加到列表中。addVertex()打印出关于顶点被添加到列表的消息,尽管它还没有这样做。然后它尝试但失败,导致ArrayList.add()抛出异常,异常在createNetwork()中被捕获,因此您不会注意到有什么问题。

不要捕捉你不会处理的异常。

最新更新