swing - problem with loop- for: java -
i'm trying change code loop, have problems
panel[1].setbackground(color.red); panel[2].setbackground(color.white); panel[3].setbackground(color.red); panel[4].setbackground(color.white); panel[5].setbackground(color.red); panel[6].setbackground(color.white); panel[7].setbackground(color.red); panel[8].setbackground(color.white); panel[9].setbackground(color.red); panel[10].setbackground(color.white); new code - for
for (int = 0; < panel.length; i++) { panel[(i*2)+1].setbackground(color.red);//i think correct, or no? panel[(i*3)+1].setbackground(color.white); //problem here } thanks
solution
for (int = 1; < panel.length; i++) { if ( % 2 == 0 ) { panel[i].setbackground(color.white); } else { panel[i].setbackground(color.red); } } or more concise expression using ternary operator:
for (int = 1; < panel.length; i++) { panel[i].setbackground( % 2 == 0 ? color.white : color.red ); } explaination
% modulo operator, i % 2 == 0 when i even, != 0 when odd.
caveats
your array of panels referencing in example starts @ 1, arrays in java start @ zero, might have potential 1 off error here if have in (first) 0 array element.
using type safe list classes better working arrays directly, not have deal 1 off error problems creating not using first array slot.
Comments
Post a Comment