【问题标题】:problem with loop- for: java循环问题:java
【发布时间】:2011-07-03 03:02:53
【问题描述】:

我正在尝试将此代码更改为 for 循环,但我遇到了一些问题

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);

新代码 - 用于

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
            }

谢谢

【问题讨论】:

  • 在循环进行时考虑(i*2)+1(i*3)+1 的值。第一次迭代是i = 0,所以它们将是(0*2)+1 = 1(0*3)+1 = 1,所以我们的开始已经很糟糕了。

标签: java swing loops for-loop


【解决方案1】:

解决方案

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

或者使用三元运算符的更简洁的表达式:

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

说明

% 是模运算符,i % 2 == 0i 为偶数时,!= 0 为奇数。

注意事项

您的示例中引用的面板数组从 1 开始,Java 中的数组从零开始,如果(第一个)零数组元素中有任何内容,您可能会在此处遇到潜在的一次性错误。

使用类型安全的List 类总是比直接使用数组更好,您不必处理因不使用第一个数组槽而产生的一次性错误问题。

【讨论】:

  • 当你可以用 2 增加一个数组时,使用 if else 条件的要点是什么?
  • 这不适用于奇数项列表,请阅读 % 运算符的用途。
  • i % 2 == 0 ? panel[i].setBackground(Color.white) : panel[i].setBackground(Color.red); } 这不会在 java 中编译
  • @bestsss:修复它,复制粘贴原来的错误
【解决方案2】:

我愿意:

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

【讨论】:

  • 嗨!在第二个示例中,您有红色/白色,在第一个白色/红色中。即需要以红色开始(在循环之前)
  • 删除了第二个例子,因为它只会产生噪音
【解决方案3】:
for (int i = 1; i < length; i+=2)
{
    panel[i].setBackground(red);
    panel[i+1].setBackground(white);
}

【讨论】:

  • 这将导致IndexOutOfBoundsException 以及奇数项无效
【解决方案4】:
for(int i = 1; i<panel.length; i++)
{
    if(i%2 == 0)
    {
        panel[i].setBackground(Color.white);
    }
    else
    {
        panel[i].setBackground(Color.red);
    }
}

【讨论】:

    【解决方案5】:

    使用新式的 for 循环:

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

    【讨论】:

    • +1 我宁愿参考当前颜色而不是 int var 上的模运算符。这样看起来更干净了stackoverflow.com/questions/5097601/problem-with-loop-for-java/…
    • 同意@Oscar。如果您必须独立维护索引/计数,则使用迭代器毫无意义。
    • @Fel 这是什么意思? a) 有一个项目,但您不想更改它的颜色 b) 您将数组的零索引留空?
    • @Fel:你确实有一个[0],你只是没有在里面放任何东西,它仍然在那里,它会导致这个答案失败,@987654324 @
    • @Sean,您从不编写任何库代码,是吗?你确实有边界检查和绝对类型安全......另外,如果你删除位操作,java 在服务器上已经死了,没有适合你的协议
    猜你喜欢
    • 2013-04-07
    • 1970-01-01
    • 1970-01-01
    • 2019-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多