2012-09-04 68 views
0

我试图循环通过一些字符串arraylists匹配元素,但我得到一个错误,我的数组不是长度相同。我有一个阵列列表,里面有一堆样本,另外一个只有几个样本。我希望在第一个数组列表中进行搜索,并将它们与第二个数值进行比较和匹配。当我找到两个数组列表匹配的地方时,我想把第一个数组的索引应用到第三个数组中,该数组包含与样本协调的方法(作为提示存储在第一个数组中)。包括导致问题出现的代码,但尽量保持简洁。 本质上我希望有人能解释我得到的错误,或者更好的方法来比较它们。Java匹配循环

//this is how they are declared 
ArrayList<String> pit = new ArrayList<String>(); int h =0; 
...etc... 
//a file is read in 
while((sLine=inpt.readLine())!=null){ 
     splitn=sLine.split(delim2); 
     //splits the file into two different ArrayLists, names and means 
     pit.add(splitn[0]); pit2.add(splitn[2]); 
} 
String b="mean"; int pitn = 0; 
//remove column titles from those two lists 
while(pitn<pit.size()){ 
    if(pit2.get(pitn).equals(b)){ 
     pit.remove(pitn); pit2.remove(pitn); 
    } 
    else{ 
      ++pitn; 
    } 
} 
//match a pattern to the file names that were entered 
ArrayList<String> sampleNum = new ArrayList<String>();   
for(String inp : filenames) { 
    Matcher matt=patt.matcher(inp); 
    while(matt.find()){ 
      if(matt.groupCount() >= 2) { 
       //match the first part of the file name 
       samplenum = matt.group(1); 
       //match the second grouping to paneltype 
       paneltype = matt.group(2); 
      } 
      //add sample names to another arraylist 
      sampleNum.add(samplenum); 
    } 
    **//I wish to search through the pit values for a place where it matches sampleNum 
    //Problematically I am getting an error 
    //for the length of pit** 
    for(int inx=0;inx<pit.size();inx++){ 
     //if the value of pit equals the value of sampleNum 
     if(pit.get(inx).equals(sampleNum.get(h))){ 
      //add the value, of the same index, from pit2 to the mncov arraylist 
      mncov.add(pit2.get(inx)); 
      h++; 
     } 
    } 

java.lang.IndexOutOfBoundsException:指数:2,大小:2

我进入2个文件,所以这是有道理的,因为sampleNum从文件名中获取。 2档= 2的文件名

at java.util.ArrayList.RangeCheck(ArrayList.java:547) 
at java.util.ArrayList.get(ArrayList.java:322) 
at consistentbelow.ConsistentBelow.main(ConsistentBelow.java:**72**) 

线是这一行:

(pit.get(INX).equals(sampleNum.get(H))){

所以我不完全确定这里有什么问题。我觉得我失去了一些明显的东西,但是已经将它注意到了失明。我认为我提供了足够的信息来获得一些帮助,但如果这对我有帮助,我不会抱怨。

+0

所以,基本上如果字符串中的第二项是“意味着”你删除了两部分? (在代码的前半部分) – eboix

+0

@eboix如果存在字符串“mean”,那么我删除该值以及它在其他arraylist中匹配的值,因为该值将是一个字符串“SampleNum”,而我只是想要实际的手段和实际的样本编号,而不是列名。 – Stephopolis

+0

好的。而'patt'是一些预定义的模式,对吧? – eboix

回答

1

我认为你的问题不是pit的大小问题,而是sampleNum的大小问题。每当你找到一个匹配时,你正在增加h,但是没有什么能够阻止h递增到比sampleNum的总长度更长的地步(即所有东西都匹配,并且一直试图匹配)。快速修复可能是这样的

for(int inx=0; inx<pit.size() && h < sampleNum.size(); inx++){ 
    if(pit.get(inx).equals(sampleNum.get(h))){ 
     //add the value, of the same index, from pit2 to the mncov arraylist 
     mncov.add(pit2.get(inx)); 
     h++; 
    } 
} 

不是最优雅的修复,但应该消除我相信的错误。我也怀疑这可能不是你期望的输出,但很难说没有你想要做什么的更好的想法。

+2

我不打算再回答,因为这个很好。但是这可能更优雅:'for(int inx = 0; inx eboix

+0

啊,所以你看到了包含数组列表大小。感谢您的解释和所有帮助 – Stephopolis