Java-for循环未将所有元素添加到列表中

Java-for循环未将所有元素添加到列表中,java,parsing,for-loop,Java,Parsing,For Loop,我目前正在编写一个Java程序,用特殊的标记语言解析文本内容,并执行以下操作: 选择特定的内容,比如定义 删除特殊语法以获得更清晰的文本输出 我已经在代码中与for循环斗争了好几天,但我找不到问题:我的for循环将列表中的第一个元素再次添加到第二个元素,我不知道它在代码中的什么地方导致了这种错误。这段代码是“修复”几个NullPointerException的结果,它不是很漂亮,我希望你们中的一些人能够阅读并给我一个关于我的错误的提示: //we want to use the advant

我目前正在编写一个Java程序,用特殊的标记语言解析文本内容,并执行以下操作:

  • 选择特定的内容,比如定义
  • 删除特殊语法以获得更清晰的文本输出
我已经在代码中与for循环斗争了好几天,但我找不到问题:我的for循环将列表中的第一个元素再次添加到第二个元素,我不知道它在代码中的什么地方导致了这种错误。这段代码是“修复”几个NullPointerException的结果,它不是很漂亮,我希望你们中的一些人能够阅读并给我一个关于我的错误的提示:

//we want to use the advantages of both ArrayList and String Array so we will work with both types
    List<String> temp = new ArrayList<String>();
    for (String line : dr.getAllLines()){
        temp.add(line);
    }
    String[] tempArray= new String[temp.size()];
    temp.toArray(tempArray); //fill the array with the contents of the temp list

    for (int i=0; i<temp.size(); i++){//this for loop goes through the lines looking for our pattern

        //define this pattern :
        Pattern patternS = Pattern.compile("^=== (.+) ==="); //new entry is always characterized by this regex
        Matcher matcherS = patternS.matcher(tempArray[i]);

        if (matcherS.find()){ //if current line matches pattern

            for(int ii=i+1; ii<temp.size(); ii++){ //this for loop adds content to our Eintraege list (because we found the pattern)

                //clean up current line (i)
                tempArray[ii-1]=tempArray[ii-1].replaceAll("[^a-zA-ZßüöäÜÖÄ|\\s+]", "");

                //add current line (i) to temporary Eintrag_lines String
                Eintrag_lines=Eintrag_lines + "\n" + tempArray[ii-1]; 

                //define again pattern (for next entry)
                Pattern patternStop = Pattern.compile("^=== (.+) ===");
                Matcher MatcherSTOP = patternStop.matcher(temp.get(ii)); //look at next line (ii)

                if(MatcherSTOP.find()){//if we find the line corresponding to the next Eintrag

                    //Eintraege is a list of all entries for one word (one element=one entry)
                    Eintraege.add(Eintrag_lines); 

                    Eintrag_lines = ""; //clear current entry String
                    break;//stop adding to our Eintraege list and go back to 
                }

            } //this for-loop adds lines for 1 entry until it finds the first line of the next entry (MatcherSTOP)
        }   else {
            continue;
        }
    }

    return Eintraege;
}

//method
public String getSpecificEintrag(int inputNumber){ //input "1" : first element of list
    parseEintraege();
    for (int i=0;i<Eintraege.size();i++){
        System.out.println(i + Eintraege.get(i) + "\n next : \n");
    }


    //try{
    //  System.out.println(Eintraege.get(inputNumber-1));
    //  return Eintraege.get(inputNumber-1);
    //} catch (IndexOutOfBoundsException e){
    //  System.err.println("IndexOutOfBoundsException : try a smaller number for the entry");
    //}
    return "";
}
这就是我得到的:

0
 Wortart|Substantiv|Deutsch m 

Deutsch Substantiv Übersicht
|Genusm
|Nominativ SingularTon
|Genitiv SingularTons
|Genitiv SingularTones
|Genitiv PluralTone
|Dativ SingularTon
|Dativ SingularTone
|Dativ PluralTonen
|Akkusativ SingularTon
|Akkusativ PluralTone


Worttrennung
Ton Pl Tone

Aussprache
IPA Lautschrift|ton Pl Lautschrift|ton
Hörbeispiele Audio|DeTonogg Pl Audio|DeTöneogg|Tone
Reime Reim|on|Deutsch

Bedeutungen
 feinkörniges Verwitterungsprodukt Bodenart Töpfermaterial

Herkunft
Durch Verdumpfung von  zu  aus dem frühneuhochdeutschen tahen than welches wiederum aus dem spätmittelhochdeutschen dhe the Genitiv dhen then Lehm althochdeutsch thha Ton Lehm Töpfererde irdenes Gefäß hervorgegangenen war Belegt seit der Zeit um  Verwandt sind das mittelniederdeutsche d das altenglische  he und gotisch h Ton Lehm Allen zugrunde liegt des protogermanische germ anhn beim Trocknen schrumpfende dichter werdende Erde Während die frühen Formen noch feminin waren fand ein Genuswechsel zum maskulinen Genus wohl in Anlehnung an Lehm statt refLiteratur|AutorWolfgang Pfeifer Leitung|TitelEtymologisches Wörterbuch des Deutschen|Auflage durchgesehene und erweiterte|VerlagDeutscher Taschenbuch Verlag|OrtMünchen|Jahr|ISBN Stichwort supsupTonref

Synonyme
 Lehm Mergel

Beispiele
 Der Boden hier besteht zum größten Teil aus Ton

Wortbildungen
 tönern Tonerde Tonpfeife Tontaube

 Übersetzungen 
ÜTabelle|Ülinks
en  Ü|en|clay
fr  Ü|fr|argile f
it  Ü|it|argilla f
ca  Ü|ca|argila f
pl  Ü|pl|glina f  Ü|pl|i m
pt  Ü|pt|argila f
|Ürechts
ro  Ü|ro|lut
ru  Üt|ru||
sv  Ü|sv|lera
es  Ü|es|arcilla f
hu  Ü|hu|agyag


Referenzen
 Wikipedia|Ton
 RefDWDS|Ton
 RefDuden|TonSediment|Ton Sediment
 RefCanoo|Ton
 RefUniLeipzig|Ton

Quellen



 next : 

所以我只得到第一个条目。也许这个错误非常愚蠢和简单,但我就是看不出来

非常感谢,很抱歉发了这么长的帖子


注:如果您需要一些德语单词或变量名的翻译,请告诉我。

我将用一个粗略的提纲来扩展我的评论,我将做些什么来简化/改进事情:

//your Eintraege
List<String> entries = ...; 

//compile the pattern only once
Pattern startPattern= Pattern.compile("^=== (.+) ===");

//use a StringBuilder for better performance
StringBuilder entry = new StringBuilder();  
boolean inEntry = false;

for (String line : dr.getAllLines()){   
  //you could also create the matcher outside and call matcher.reset(line) instead
  Matcher matcher = startPattern.matcher( line );

  if( matcher.find() ) {
    if( inEntry ) {
      //we're in an entry already so add the current and start a new one
      entries.add( entry.toString() );
      entry.clear();
    }

    //now we're definitely in an entry
    inEntry = true;
  }
  //no entry start but in an entry already 
  else if( inEntry ) {
    //apply whatever replacements you want and add the line to the current entry
    entry.append( line.replace("foo", "bar" ) );
  }
}

//if we're still in an entry here we need to add it as it didn't already happen in the loop
if( inEntry ) {
   entries.add( entry.toString() );
   entry.clear();
}
//您的eIntrage
列表条目=。。。;
//只编译模式一次
模式startPattern=Pattern.compile(“^===(.+)==”);
//使用StringBuilder可获得更好的性能
StringBuilder条目=新建StringBuilder();
布尔值=假;
对于(字符串行:dr.getAllLines()){
//您也可以在外部创建matcher并调用matcher.reset(line)
匹配器匹配器=起始模式匹配器(行);
if(matcher.find()){
如有(内地){
//我们已经在一个条目中,所以添加当前条目并开始一个新条目
entries.add(entry.toString());
entry.clear();
}
//现在我们肯定进入了一个项目
真实=真实;
}
//没有条目开始,但已在条目中
如有其他情况(印度){
//应用所需的任何替换项,并将该行添加到当前条目
条目。追加(行。替换(“foo”,“bar”));
}
}
//如果我们仍然在一个条目中,我们需要添加它,因为它在循环中还没有发生
如有(内地){
entries.add(entry.toString());
entry.clear();
}
正如您所看到的,您的代码有一些不同之处:

  • 不需要任何额外的列表或数组
  • 模式只编译一次(无需多次编译)
  • 无需查看下一步,只需根据当前线路做出反应

对于此行:
For(字符串行:dr.getAllLines()){
什么是
dr
?你调试了你的代码吗?你找到了
eintrage
有多少项了吗?我怀疑有一项。
//我们想利用ArrayList和String数组的优点,所以我们将使用这两种类型
-为了让你的代码更简单,请考虑一下这些优点。我想说的是没有任何东西可以证明使用列表和等效数组更有可能导致错误。您似乎也会在内容行上循环两次,即
i从0到temp.size()-1
和在内部循环中
ii从i+1到temp.size()-1
,因此您至少会触摸第二行两次,第三行三次,等等。
//your Eintraege
List<String> entries = ...; 

//compile the pattern only once
Pattern startPattern= Pattern.compile("^=== (.+) ===");

//use a StringBuilder for better performance
StringBuilder entry = new StringBuilder();  
boolean inEntry = false;

for (String line : dr.getAllLines()){   
  //you could also create the matcher outside and call matcher.reset(line) instead
  Matcher matcher = startPattern.matcher( line );

  if( matcher.find() ) {
    if( inEntry ) {
      //we're in an entry already so add the current and start a new one
      entries.add( entry.toString() );
      entry.clear();
    }

    //now we're definitely in an entry
    inEntry = true;
  }
  //no entry start but in an entry already 
  else if( inEntry ) {
    //apply whatever replacements you want and add the line to the current entry
    entry.append( line.replace("foo", "bar" ) );
  }
}

//if we're still in an entry here we need to add it as it didn't already happen in the loop
if( inEntry ) {
   entries.add( entry.toString() );
   entry.clear();
}