2011-11-19 98 views
0

對於此任務,我應該創建一個應該是圖形的「wannabe」網絡。您讀取的第一個文件包含一個帶有來自/的頂點的文本文件以及其他一些數據。我還有一個內部計數器,用於計算addVertex已被使用的次數。到目前爲止,這是正確的,測試打印是正確的,但是當我運行它時,列表中沒有任何頂點,即使它表示它已被添加。 任何想法爲什麼id不會添加到它的列表和任何想法?讀取頂點並創建邊緣

這裏是我讀:

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>(); 
    } 

} 

回答

1

他們沒有加入到列表第一名。 addVertex()會打印出有關要添加到列表中的頂點的消息,但它尚未完成此操作。然後它嘗試但失敗,導致ArrayList.add()異常被異常抓到createNetwork(),所以你不會注意到出了什麼問題。

不要捕捉你不會處理的異常。不要在執行操作前記錄操作。