2015-05-07 41 views
0

在這個類中,我得到了存儲在數據庫中的公共汽車站列表的名稱,並且我想將它們顯示在組合框中。但我得到以下錯誤:數組列表「獲取」問題

GET方法(INT)在ArrayList類型不適用的參數(字符串)

有什麼建議?

// gets the stop names from the database 
    int[] routeArray = BusStopInfo.getRoutes(); 
    int[] stopIdArray; 
    ArrayList<String>stopName = new ArrayList<String>(); 
    for(int i = 0; i < routeArray.length; i++) { 
     stopIdArray = BusStopInfo.getBusStops(i); 
     for (int j = 0; j < stopIdArray.length; j++) { 
      stopName.add(BusStopInfo.getFullName(stopIdArray[j])); 
     }//for 
    } // for 
    String[] nameArray = new String[stopName.size()]; 
    nameArray = stopName.toArray(nameArray); 
    for (int k = 0; k < stopIdArray.length; k++){ 
     stopListDeparture = stopName.get(nameArray[k]); 
    } 

    stopListDeparture.setSelectedIndex(0); 
    setLayout(new BorderLayout()); 
    add(stopListDeparture, BorderLayout.NORTH); 
+0

嘗試'字符串str =(字符串)stopName.get(K);' – ryekayo

+0

使用'Map'用於存儲 –

+0

爲更好地幫助更快張貼SSCCE/MCVE,短,可運行的,可編譯的,與硬編碼值在局部變量中使用Swing GUI – mKorbel

回答

0

當你這樣做stopName.get(nameArray[k]);,nameArray [K]是String。你需要做的stopName.get(Integer.parseInt(nameArray[k]));

+0

雖然如此,但我會更改'nameArray'的名稱,因爲我認爲它是一個名稱數組,名稱不是(通常)數字... – dcsohl

+0

完全同意。但'stopName'不是一個很好的變量名;)。 – Tavo

0

烏爾問題是在下面一行

stopListDeparture = stopName.get(nameArray[k]); 

nameArray [K]返回一個字符串,並且您正在嘗試從使用列表中選擇一個特定的元素。根據Java Documentation get方法接受一個int並返回該列表中指定位置的元素。

1

我打算用一個不同的建議從其他答案出發。考慮到這些線路:

nameArray = stopName.toArray(nameArray); 
for (int k = 0; k < stopIdArray.length; k++){ 
    stopListDeparture = stopName.get(nameArray[k]); 
} 

要轉換列表,stopNameString數組,然後通過循環訪問數組,並獲得該...對應於本身數組中的項目?你確定這就是你的意思嗎?

而不是stopName.get(nameArray[k])我想也許你應該是stopName.get(stopIdArray[k])。與nameArray不同,stopIdArray實際上是一個int s的數組,所以這會編譯並運行得很好。

這裏的贈品是,你從0到stopIdArray的長度迭代,而是從不同的陣列(nameArray)獲取元素。有時候這就是你的意思,但通常這是一種代碼味道。

+0

+1,我只是寫了類似的東西,但你打敗了我。被複制到數組中的ArrayList似乎相當多餘。 – berry120

0

我發現了這樣做的方式。我宣佈JComboBox爲。 感謝大家的回答。

JComboBox<String> stopListDeparture = new JComboBox<String>(); 

    int[] routeArray = BusStopInfo.getRoutes(); 
    int[] stopIdArray = new int[0]; 
    ArrayList<String>stopName = new ArrayList<String>(); 

    for(int i = 0; i < routeArray.length; i++) { 
     stopIdArray = BusStopInfo.getBusStops(routeArray[i]); 
     for (int j = 0; j < stopIdArray.length; j++) { 
      stopName.add(BusStopInfo.getFullName(stopIdArray[j])); 
     }//for 
    } // for 
    String[] nameArray = stopName.toArray(new String[stopName.size()]); 
    nameArray = stopName.toArray(nameArray); 
    for (int k = 0; k < stopIdArray.length; k++){ 
     stopListDeparture = new JComboBox<String>(nameArray); 
    } 

    stopListDeparture.setSelectedIndex(0); 
    setLayout(new BorderLayout()); 
    add(stopListDeparture, BorderLayout.NORTH);