【问题标题】:How to change a variable every iteration of a loop (Java)如何在循环的每次迭代中更改变量(Java)
【发布时间】:2013-05-15 14:23:27
【问题描述】:

如何在每次循环后更改我的变量。我需要将声明的arraylist 变量放到代码标记为“HERE”的位置。

//variables i need to cycle through
static ArrayList<Integer> one1,two1,one2,two2=new ArrayList<>();

for(int i=0;i<4;i++){
  for(int j=0;j<word1[i].length();j++){
    if (word1[i].charAt(j)=='-'){
      HERE.add(j);
    } else if (word1[i].charAt(j)!='-') {
      HERE.add(null);
    }
  }
}

有没有一种简单的方法可以在没有几十行代码的情况下做到这一点?

【问题讨论】:

  • 请澄清您的问题。
  • 也许您可以使用列表映射或其他数据结构。

标签: java variables loops char int


【解决方案1】:

将您的列表放入一个数组中。

for(List<Integer> HERE: new List<Integer>[]{ one1,two1,one2,two2})

【讨论】:

    【解决方案2】:

    您可以创建自己的 here 方法,为您添加到多个列表中,如下所示:

    package com.sandbox;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class Sandbox {
    
    
        public static void main(String[] args) {
            List<Integer> l1 = new ArrayList<Integer>();
            List<Integer> l2 = new ArrayList<Integer>();
            List<Integer> l3 = new ArrayList<Integer>();
            here(1, l1, l2, l3);
        }
    
        public static void here(Integer integer, List<Integer>... lists) {
            for (List<Integer> list : lists) {
                list.add(integer);
            }
        }
    
    }
    

    ... 称为可变参数,you can learn more about it here. 每次在当前代码中有 HERE.add 时调用它,如下所示:here(j, one1, two1, one2, two2)

    但我认为你可能在这里做错了什么。你为什么要这样做?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-30
      • 1970-01-01
      • 2021-11-03
      • 2019-08-16
      • 2018-05-23
      • 2020-08-07
      • 1970-01-01
      • 2021-12-08
      相关资源
      最近更新 更多