If I search for the 5th item in my arrayList, I also want to get the 4th and 6th. The code for this is provided in the final if statement and is define as (i – 1) and (i + 1). Here is my code so far:
import java.util.ArrayList;
public class PlanetsList {
public static void main(String args[]) {
ArrayList<String> planets = new ArrayList<String>();
String names[] = { "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranis", "Neptune", "Pluto"};
for (int i = 0, n = names.length; i < n; i++) {
planets.add(names[i]);
String value = (String) planets.get(i);
if(value.contains("Mars")) {
String newNum = value.replace(value, "Red planet ");
planets.set(i,newNum);
}
if(value.contains("Uranis")) {
String wordBefore = (String) planets.get(i-1);
String wordAfter = (String) planets.get(i+1);
String newNum = value.replace(value, "Uranus ");
planets.set(i,newNum);
System.out.println("This is the word before " + wordBefore);
System.out.println("This is the word after " + wordAfter);
planets.remove(i-1);
}
}
System.out.println(planets);
}
}
With this I get an indexoutofbounds exception, which is obviously caused by the wordAfter line in the final if statement, and because the for loop hasn’t looped through the entire arrayList. The final if statement doesn’t need to be in the same for loop as the other if statement, but if it is in a different loop, the replace method must be able to put the replaced word back in the correct position.
Regards
Complete adding the strings into your list and then try iterating over list again for your logic. You’re trying
get(i+1)wheniis the max added to your list.