anvd
anvd

Reputation: 4047

problem with loop- for: java

I'm trying to change this 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

Upvotes: 1

Views: 373

Answers (5)

user177800
user177800

Reputation:

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.

Upvotes: 3

OscarRyz
OscarRyz

Reputation: 199215

I would:

Color current = Color.white; 
for( Panel p : panels ) { 
   p.setBackground( current );
   current =  ( current == Color.white ? Color.red : Color.white );
}

Upvotes: 3

x.509
x.509

Reputation: 2235

for (int i = 1; i < length; i+=2)
{
    panel[i].setBackground(red);
    panel[i+1].setBackground(white);
}

Upvotes: -1

Owen
Owen

Reputation: 1551

for(int i = 1; i<panel.length; i++)
{
    if(i%2 == 0)
    {
        panel[i].setBackground(Color.white);
    }
    else
    {
        panel[i].setBackground(Color.red);
    }
}

Upvotes: 3

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298838

Use a new-style for loop:

int ct = 0;
for(JPanel panel : panels){
   panel.setBackground((ct % 2 == 1) ? Color.Red : Color.White);
   ct++;
}

Upvotes: 8

Related Questions