I am trying to add marker New direction
to the arrayList mergeArray
when I found the second 3
value in the buffer
arrayList but I am always getting the first 3
value in the ArrayList. How can I get the second one after Amsterdam?
I appreciate any help.
output:
paris
3
water
ball
money
Amsterdam
3
door
output should looks like this:
paris
3
water
ball
money
New direction
Amsterdam
3
door
Code:
public static void main(String[] args) {
ArrayList<String> buffer = new ArrayList<String>();
ArrayList<String> mergeArray = new ArrayList<String>();
String route = "3";
String direction = "paris";
String start = "Amsterdam";
buffer.add("paris");
buffer.add("3");
buffer.add("water");
buffer.add("ball");
buffer.add("money");
buffer.add("Amsterdam");
buffer.add("3");
buffer.add("door");
for (String line : buffer) {
if (line.equals(route)) {
mergeArray.add(line);
int index = buffer.indexOf(line);
String prevElement = buffer.get(index - 1);
if (prevElement == direction) {
String addElem = buffer.get(index + 1);
mergeArray.add(addElem);
} else if (prevElement == start) {
mergeArray.add("New direction");
}
}
}
for (String key : mergeArray) {
System.out.println(key);
}
}
Do not use
indexOf
as it will always retrieve the index of the first appearance.Keep an auxiliary index variable and use it in your loop:
also add safety checks so the index will not under/over-flow