【发布时间】:2013-01-07 23:17:38
【问题描述】:
如果我在我的 arrayList 中搜索第 5 项,我还想获得第 4 项和第 6 项。最终的 if 语句中提供了此代码,并定义为 (i - 1) 和 (i + 1)。到目前为止,这是我的代码:
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);
}
}
这样我得到了一个 indexoutofbounds 异常,这显然是由最终 if 语句中的 wordAfter 行引起的,并且因为 for 循环没有遍历整个 arrayList。最后的 if 语句不需要和另一个 if 语句在同一个 for 循环中,但如果它在不同的循环中,replace 方法必须能够将被替换的单词放回正确的位置。
问候
【问题讨论】:
-
使用泛型类型来避免强制转换:
ArrayList<String> planets = new ArrayList<>();,另外,为什么在检查相等性时在字符串上使用contains()?这就是equals()的用途;)另外,我不认为你的问题是不言自明的。你真正想做什么? -
这只是我的程序的一部分,而不是实际的东西。需要 contains 方法用于其他目的。将调整为通用类型并查看我的问题。
标签: java for-loop arraylist indexoutofboundsexception