【问题标题】:Declaring a variable in a for loop using the index (i)使用索引 (i) 在 for 循环中声明变量
【发布时间】:2012-02-01 00:45:59
【问题描述】:

我非常接近让这个项目开始工作,但我被一件让我发疯的事情困住了,我在我的研究中找不到任何有效的东西。

我需要做的是每次for循环通过记录集时声明一个新变量,但是我需要在变量名中使用索引值(i)。

我需要帮助的是Bottles o[i] = new Bottles();

每次 for 循环再次通过时,我都需要定义一个新变量,例如,我的变量最终应该是 o1、o2、o3 等。我现在在 [i] 上遇到语法错误而且我似乎不知道该怎么做。

对我在这里缺少什么有什么想法吗?

private void getBottles() {
        try {
            m_bottles = new ArrayList<Bottles>();
            for (int i = 0; i < bottleNamesMap.size(); i++) {
                Bottles o[i] = new Bottles();
                o[i].setbottleID(bottleIntMap.get("bottleID" + i));
                o[i].setname_abbr(bottleNamesMap.get("name" + i));
                o[i].setorigin(bottleNamesMap.get("origin" + i));
                o[i].setbottlePicture(bottleNamesMap.get("bottlePicture" + i));
                o[i].setprice_reported(bottleNamesMap.get("price" + i));
                o[i].setdistillery(bottleNamesMap.get("distillery" + i));
                o[i].setagg_score(bottleIntMap.get("aggscore" + i));
                m_bottles.add(o[i]);
                Thread.sleep(2000);
                Log.i("ARRAY", "" + m_bottles.size());
            }
          } catch (Exception e) {
            Log.e("BACKGROUND_PROC", e.getMessage());
          }
          runOnUiThread(returnRes);
      }

【问题讨论】:

  • 请注意,您不能在运行时命名变量。你唯一能做的就是从列表 o 中获取一个元素,使用 i 作为索引。返回值是对瓶子的未命名引用。此外,我应该非常仔细地看看“瓶子”实际上代表什么,我当然建议您阅读 Java 命名约定oracle.com/technetwork/java/codeconventions-135099.html#367

标签: java android variables dynamic loops


【解决方案1】:
 Bottles o[i] = new Bottles();

应该是:

  Bottles o = new Bottles();

然后删除[i]。 new 关键字将在每次迭代中创建一个新对象。

            Bottles o = new Bottles();
            o.setbottleID(bottleIntMap.get("bottleID"+i));
            o.setname_abbr(bottleNamesMap.get("name"+i));
            o.setorigin(bottleNamesMap.get("origin"+i));
            o.setbottlePicture(bottleNamesMap.get("bottlePicture"+i));
            o.setprice_reported(bottleNamesMap.get("price"+i));
            o.setdistillery(bottleNamesMap.get("distillery"+i));
            o.setagg_score(bottleIntMap.get("aggscore"+i));
            m_bottles.add(o);

【讨论】:

    【解决方案2】:

    只需使用:

    Bottles o = new Bottles();
    

    【讨论】:

      【解决方案3】:

      您不需要变量名中的索引 - 这只是用于编译器。你可以说

      瓶子 = new Bottles();

      然后在使用 o[i] 的任何地方都使用瓶子;

      每次循环都会创建一个新的 Bottles - 尽管变量名称相同,但它是一个不同的对象,您可以稍后通过 ArrayList 对其进行索引。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-22
        • 1970-01-01
        • 2011-05-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多