【问题标题】:Replacing Variable Name per Loop Cycle每个循环周期替换变量名
【发布时间】:2019-05-07 16:04:16
【问题描述】:

正如标题所说,我需要将变量名称的一部分替换为for循环迭代的次数。

在我的代码中,变量是 Swing 上的按钮网格,从 a1 到 c3。我必须重新着色依赖于 p1grid[] 数组的所有按钮。我不能(据我所知)将它们放在自己的数组中,因为它们是按钮。这是我的代码:

for (int i = 1; i < 4; i++) {
    if (p1grid[i - 1].equals("empty"))
        ("a" + i).setBackground(Color.LIGHT_GRAY);
    else
        ("a" + i).setBackground(Color.RED);
}

【问题讨论】:

  • 将按钮放入数组或地图中。他们是按钮并没有阻止你这样做。
  • 您可以将它们放在一个数组中。请记住,您必须单独添加它们,而不是整个数组一起添加(在数组上循环并添加每个数组)。

标签: java for-loop variables


【解决方案1】:

您当前的代码将无法编译,因为 ("a"+i) 是一个没有 setBackground() 方法的字符串。

假设按钮的类是 Button。 因此,您可以执行以下操作:

   List<Button> buttons = new ArrayList<Button>;
   buttons.add(a1);buttons.add(a2);...

然后修改背景使用:

for (int i = 1; i < 4; i++) {
    if (p1grid[i - 1].equals("empty"))
        buttons.get(i-1).setBackground(Color.LIGHT_GRAY);
    else
         buttons.get(i-1)..setBackground(Color.RED);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-27
    • 2015-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-12
    • 2012-08-28
    相关资源
    最近更新 更多