2014-09-01 88 views
-1

我的代碼數組。如何在數組中插入項目?如何在數組中插入項目?

int listElemCount = jCBWorkerMen.getItemCount(); 
Object[] selectionValues = null; 
for (int i = 0; i < listElemCount; i++) { 
     selectionValues[i] = (Object[]) jCBWorkerMen.getItemAt(i); 
     System.out.println(selectionValues); 
    } 
String initialSelection = "Dogs"; 
Object selection = JOptionPane.showInputDialog(null, "What are your favorite animals?", "Zoo Quiz", JOptionPane.QUESTION_MESSAGE, null, selectionValues, initialSelection); 
System.out.println(selection); 
+5

使用'List',如'ArrayList',假設你的意思是你想改變數組的長度.. – MadProgrammer 2014-09-01 05:15:05

+1

如果你想插入(添加,改變長度等)數組,請使用'List ',參見http://stackoverflow.com/questions/2697182/how-to-use-an-array -list – jdphenix 2014-09-01 05:17:27

+1

另外,「jCBWorkerMen」的類型是什麼? – jdphenix 2014-09-01 05:18:58

回答

0

像下面

public static void main(String[] args) { 

     List<Integer> list = new ArrayList<Integer>(); 
     list.add(1); 
     list.add(2); 
     list.add(3); 
     list.add(4); 
     list.add(5); 
     list.add(6); 
     list.add(7); 
     list.add(8); 
     list.add(9); 
     list.add(10); 

     Object[] selectionValues = new Object[list.size()]; 
     for (int i = 0 ; i < list.size() ; i++) { 
      selectionValues[i] = list.get(i); 
     } 

     for (int i = 0 ; i < selectionValues.length ; i++) { 
      System.out.println(selectionValues[i]); 
     } 
    } 
0

你的算法不正確,這

int listElemCount = jCBWorkerMen.getItemCount(); 
Object[] selectionValues = null; 
for (int i = 0; i < listElemCount; i++) { 
    selectionValues[i] = (Object[]) jCBWorkerMen.getItemAt(i); 
    System.out.println(selectionValues); 
} 

需要通過初始化數組開始。另外,在完成初始化之前,您可能不應該打印陣列。最後,您需要使用Arrays.toString(Object[]),因爲Java陣列不會覆蓋toString()。因此,像,

int listElemCount = jCBWorkerMen.getItemCount(); 
Object[] selectionValues = new Object[listElemCount]; 
for (int i = 0; i < listElemCount; i++) { 
    selectionValues[i] = jCBWorkerMen.getItemAt(i); 
} 
System.out.println(Arrays.toString(selectionValues)); 
0

變化碼應該像如下

int listElemCount = jCBWorkerMen.getItemCount(); 
    Object[] selectionValues = new Object[listElemCount]; 
    for (int i = 0; i < listElemCount; i++) { 
      selectionValues[i] = jCBWorkerMen.getItemAt(i); 
      //System.out.println(selectionValues); 
     } 
    //to view the all the items in the array 
    for (int i = 0; i < listElemCount; i++) {    
      System.out.println(selectionValues[i]); 
    } 
    String initialSelection = "Dogs"; 
    Object selection = JOptionPane.showInputDialog(null, "What are your favorite animals?", "Zoo Quiz", JOptionPane.QUESTION_MESSAGE, null, selectionValues, initialSelection); 
    System.out.println(selection); 
+0

非常感謝。我喜歡你的答案! – Arslanali 2014-09-01 07:09:42