[英]How to change a variable every iteration of a loop (Java)
How can I have my variables change after every loop. 每次循环后如何更改变量。 I need the stated arraylist variables to go where the code is marked "HERE".
我需要声明的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);
}
}
}
Is there a simple way i could do this without dozens of lines of code? 没有几十行代码,有没有一种简单的方法可以做到这一点?
You can create your own here
method that adds to multiple lists for you like this: 您可以创建自己的
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);
}
}
}
The ...
is called a varargs and you can learn more about it here. ...
称为varargs, 您可以在此处了解更多信息。 Just call this every time you have HERE.add
in your current code like this: here(j, one1, two1, one2, two2)
每次有
HERE.add
时都调用此HERE.add
在当前代码中添加如下所示: here(j, one1, two1, one2, two2)
But I think you're probably doing something wrong here. 但是我认为您可能在这里做错了。 Why do you want to do this?
为什么要这样做?
将您的列表放入数组。
for(List<Integer> HERE: new List<Integer>[]{ one1,two1,one2,two2})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.