Reputation: 251
years = new String[67];
for(int y = cal.get(Calendar.YEAR) - 13; y <= cal.get(Calendar.YEAR) - 80; y++) {
for(int i = 0; i < years.length; i++){
years[i] = Integer.toString(y);
}
}
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(years));
I have this code for populating ComboBox with 67 dates however all I'm getting is empty values?
Upvotes: 0
Views: 4663
Reputation: 420991
The body of the outer loop will never execute since the loop condition is false on the first iteration:
You try to go from x - 13
up to x - 80
.
for(int y = cal.get(Calendar.YEAR) - 13; y <= cal.get(Calendar.YEAR) - 80; y++)
^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^
this is higher than... ...this even in the first iteration
Also, to make sure -13
to -80
actually adds up to the length of the years
array, I'd suggest you write it like this:
String[] years = new String[67];
int thisYear = cal.get(Calendar.YEAR);
int startYear = thisYear - 13;
for (int i = 0; i < years.length; i++)
years[i] = Integer.toString(startYear - i);
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(years));
Upvotes: 4
Reputation: 2800
Several issues jump out at me:
One, your loop executes exactly 0 times since cal.get(Calendar.YEAR) - 13
<= cal.get(Calendar.YEAR) - 80
so the loop will exit immediately.
Two, since you are going from a larger value (cal.get(Calendar.YEAR) - 13
) to a smaller one (cal.get(Calendar.YEAR) - 80
), you should not do y++
since it will increase y, you should instead use y--
.
Finally, for(int i = 0; i < years.length; i++)
will replace ALL of the values in years.
Upvotes: 0
Reputation: 691735
Supposing that the calendar is initialized with the current time, you go from year 1999 to year 1932. That makes an empty loop.
And what's the point in having those two nested loops?
Upvotes: 1
Reputation: 47608
Your for-loop end condition is true at the first iteration. Use this instead:
years = new String[67];
for(int i = 0; i < years.length; i++){
years[i] = Integer.toString(cal.get(Calendar.YEAR) - 13-i);
}
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(years));
Upvotes: 0
Reputation: 1919
for(int y = cal.get(Calendar.YEAR) - 13; y >= cal.get(Calendar.YEAR) - 80; **y--**) {
Upvotes: 0
Reputation: 11090
years = new String[67];
int index = 0;
for(int y = cal.get(Calendar.YEAR) - 13; y >= cal.get(Calendar.YEAR) - 80; y--) {
years[index++] = Integer.toString(y);
}
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(years));
Upvotes: 0