2014-10-08 32 views
0

我有一個包含DVD列表的JSP,並希望將選定列表(複選框)發送到第二個頁面進行處理。在我已經使用的第二頁中:如果我有索引,從地圖獲取關鍵字或值

String selected[] = request.getParameterValues("checkboxGroup"); 

獲取所選複選框的列表。我想獲得選定索引的關鍵OR值(bse我正在創建表)。例如;如果用戶選擇了第一個複選框,我希望能夠訪問Pirates或299.

我將一個2d數組轉換成一個映射,如下所示,如果我能夠獲得映射的索引I將能夠訪問無論是鍵或值如下:

String [ ][ ] myArray = { 
          {"Pirates", "299"}, 
          {"Travellers", "145"}, 
          {"Zoopy", "89"}, 
          {"Farewell", "67"}, 
          {"Junies", "98"}, 
          {"WakUp", "55"}, 
          {"Space", "100"}, 
          {"Solar", "199"}, 
          {"Strom", "200"}, 
          {"Wind", "200"} 
         }; 

final Map<String, String> map = new HashMap<String, String>(myArray.length); 
for (String[] mapping : myArray) { 
    map.put(mapping[0], mapping[1]); 
} 

不過,我卡住了,不知道從哪裏去,此地將那些更有經驗的升值建議。

回答

1

地圖沒有索引,所以你必須放棄這個想法。

您需要使用索引數據結構,例如List或數組。也許包含字符串和整數值的自定義對象的List會是合適的?

0

地圖的鍵/值/條目集是(如您注意的)集合,意思是無序列表。所以你實際上可以將它們解析爲帶有索引的列表,但是元素的索引不會一致。

0

終於..這是我用來代替;

TreeMap dvdstree = new TreeMap(); 

// Add some dvds. 
dvdstree.put("Pirates", 5);dvdstree.put("Solar",124); 
dvdstree.put("Travellers",145);dvdstree.put("Zoopy", 89); 
dvdstree.put("Farewell", 67); 


//Get a set of the entries 
Set set = dvdstree.entrySet(); 
// Get an iterator 
Iterator iterator = set.iterator(); 

//Used a count keep track of iteration -> compare with name of checkbox 
int count = 0; 

//Printing into html table 
out.print("<table>"); 

//Gets the selected checkboxes from previous page 
String selected[] = request.getParameterValues("checkboxGroup"); 

while(iterator.hasNext()) { 
Map.Entry me = (Map.Entry)iterator.next(); 
//used a count to keep a track of where I am in the List 
count++; 

    for(int i=0; i<selected.length; i++){ 
    if(count == Integer.parseInt(selected[i])){ 
    out.print("<tr><td>"+ me.getKey()+ "<td>"+me.getValue()+"<td/></tr>"); 
    //Used this to get value of checkbox so that I could perform arithmetic in my class 
    String value= (me.getValue()).toString(); 
    double valueDouble = Double.parseDouble(value); 
    myBean.addPrice(test2); 
    } 
    } 
} 

out.print("<tr><td>Total</td><td>"+myBean.getTotal()+"</td>"); 
out.print("</table>"); 
相關問題