2017-05-08 33 views
0
I have this code sample. 

    JComboBox[] set = {jComboBox1, jComboBox2, jComboBox3};   
     for (int i = 0; i < set.length; i++) { 

      JComboBox boxes = set[i]; 
      int index = boxes.getSelectedIndex(); 

      if (index == 0) {  

       System.out.println("Not every JcomboBox has something selected");      
       continue; 

      } else { 

       System.out.println("Every combobox has selected something"); 

      } 

我知道每次for loop運行時,它會檢查選定的值每JComboBox的。如果至少有一個JComboBox選擇了某項(除0之外的所有其他索引),它將不會執行if語句,因此它將轉至else語句。 但我需要打印 - 每一個組合框中選擇了一些 -聲明,當且僅當所有JComboBoxes選擇一些(任何索引以外的索引0),但不其中的任何已選擇的東西(即任何索引不是0)檢查所有JComboBoxes有什麼選擇任何指標(除指數0)

任何人都可以請幫助我嗎?

+0

首先計算出紙上的邏輯。提示:在for循環中使用for循環之前,您需要一個變量*。 –

+0

非常感謝主席先生:) – CodingBeginner

回答

2

嘗試使用flag變量。

boolean allSelected = true; //Initially set it to true which indicates that all selected values are other than 0 
for (int i = 0; i < set.length; i++) { 

    JComboBox boxes = set[i]; 
    int index = boxes.getSelectedIndex(); 

    if (index == 0) {  
     allSelected = false; //If index is 0, make it false 
    } 
} 

if(allSelected) 
{ 
    System.out.println("Every combobox has selected something"); 
} 
else 
{ 
    System.out.println("Not every JcomboBox has something selected"); 
} 
+1

非常感謝:) – CodingBeginner