problem with loop- for: java
I'm trying to change this 开发者_Go百科code to a for loop, but i have some 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 i = 0; i < panel.length; i++) {
panel[(i*2)+1].setBackground(Color.red);//i think that is correct, or no?
panel[(i*3)+1].setBackground(Color.white); //problem here
}
thanks
Use a new-style for loop:
int ct = 0;
for(JPanel panel : panels){
panel.setBackground((ct % 2 == 1) ? Color.Red : Color.White);
ct++;
}
Solution
for (int i = 1; i < panel.length; i++)
{
if ( i % 2 == 0 ) { panel[i].setBackground(Color.white); }
else { panel[i].setBackground(Color.red); }
}
Or a more concise expression using the ternary operator:
for (int i = 1; i < panel.length; i++)
{
panel[i].setBackground( i % 2 == 0 ? Color.white : Color.red );
}
Explaination
%
is the modulo operator, i % 2 == 0
when i
is even, != 0
when odd.
Caveats
Your array of panels referencing in your example starts at 1, arrays in Java start at ZERO, you might have a potential one off error here if you have anything in the (first) ZERO array element.
Using the type safe List
classes is always better than working with arrays directly, you would not have to deal with the one off error problems you are creating by not using the first array slot.
for(int i = 1; i<panel.length; i++)
{
if(i%2 == 0)
{
panel[i].setBackground(Color.white);
}
else
{
panel[i].setBackground(Color.red);
}
}
I would:
Color current = Color.white;
for( Panel p : panels ) {
p.setBackground( current );
current = ( current == Color.white ? Color.red : Color.white );
}
for (int i = 1; i < length; i+=2)
{
panel[i].setBackground(red);
panel[i+1].setBackground(white);
}
精彩评论