2013-05-02 78 views
1

我正在研究一個在用戶輸入的一系列頂點及其邊權重上實現Dijkstra算法的程序。我不知道在用戶輸入數據之前用戶要輸入多少個頂點。 (第一輸入值中的一個將是頂點的總數)我的問題是,我不知道如何在沒有硬編碼的東西,如爲每個頂點節點:創建未知數量的節點Java

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

我轉換的ArrayList爲整數數組一個根本沒有任何作用的嘗試,但決定留在代碼中,以防止它在這裏幫助我

+0

爲什麼不嘗試使用Vertex的**數組**? – Castiblanco 2013-05-02 21:25:03

+0

你能發表你迄今爲止寫的嗎?聽起來像你在創建基於用戶輸入的頂點時遇到麻煩。但是不知道你的用戶輸入機制是什麼樣的,很難提供任何幫助 – paulk23 2013-05-02 21:25:30

回答

0

在用戶輸入它們並將它們添加到列表中時創建頂點。

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

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

createVertexFromString是你自己寫的,很明顯的方法。