[英]Multiple if statement to add to arrayList java
I am reading in a textfile into my class. 我正在将文本文件读入我的班级。 I would like to add to a specific arrayList when the if condition is met. 如果要满足if条件,我想添加到特定的arrayList中。 At the moment the arrayList keeps on being written over and I don't know why. 目前,arrayList继续被覆盖,我不知道为什么。 Here is the code: 这是代码:
The calling class: 调用类:
public String PatternPDF (String s) throws IOException, ClassNotFoundException {
ArrayList<String>arr=new ArrayList<String>();
for (String line : Files.readAllLines(Paths.get("Fields2Extract.txt"))){
//System.out.println(line);
arr.add(line);
}
for (String pattern:arr){
OrganisePDF(pattern,s);
}
return pattern;
}
The arrayList class arrayList类
public void OrganisePDF (String pattern,String s) {
ArrayList<String> Chicago =new ArrayList<String>();
Pattern patternorganise = Pattern.compile(pattern);
Matcher matcherpatternorganise_pattern = patternorganise.matcher(s);
String h="";
while (matcherpatternorganise_pattern.find()){
h=matcherpatternorganise_pattern.group(0);
all.add(h);
}
for (String n:all){
if(n.contains("something good")||n.contains("a load of buses")){
n=n.replaceAll("\\n", "").trim();
Chicago.add(n);
}
}
System.out.prinln("Chicago"+Chicago);
}
This gives me 这给我
Chicago[something good]
Chicago[a load of buses]
Whereas I'm hoping for 而我希望
Chicago[something good,a load of buses]
You are getting this because you are not concatenating the results in the match of the regex. 之所以得到这个,是因为您没有在正则表达式的匹配中并置结果。
try something like appending the match in a stringbuilder and after the for loop add it to chicago list: 尝试将匹配项附加到stringbuilder中,然后在for循环后将其添加到芝加哥列表中:
StringBuilder sb = new StringBuilder();
for (String n:all){
if(n.contains("something good")||n.contains("a load of buses")){
n=n.replaceAll("\\n", "").trim();
sb.append(n);
}
}
Chicago.add(sb.toString());
list.add(1, object1)
StringBuilder builder = new StringBuilder();
for (String n:all){
if(n.contains("something good")||n.contains("a load of buses")){
n=n.replaceAll("\\n", "").trim();
builder.append(n);
Chicago.add(0,builder.toString()); //this will add the data to a specific position
}
}
i dont know why you want to do this weird thing , but you can try it this way chicago.add(0,ojec);
我不知道为什么你想做这个奇怪的事情,但是你可以这样尝试chicago.add(0,ojec);
this will add data to given position each time its called. 每次调用都会将数据添加到给定位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.