2013-05-20 200 views
-1

如何在每次循环后更改我的变量。我需要指定的ArrayList变量去代码标记为“HERE”的地方。如何在循环的每次迭代中更改变量(Java)

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

有没有一个简单的方法,我可以做到这一点,没有几十行代码?

+5

请澄清一下您的问题。 –

+0

也许你可以使用列表或其他数据结构的地图。 –

回答

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)

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

相关问题