使用Java程序获取ArrayIndexOutOfBounds错误,该程序试图根据以前的决定猜测下一个选择(正面或反面)
我正在制作一个程序,试图根据之前的决定猜测你是选择正面(h)还是反面(t)。程序在前3次猜测“h”,然后查找玩家的最后两个选择,通过前面的选择找到相同的决策组合,并计算哪个决策(h或t)最多次遵循相同的组合,然后选择该决策作为猜测。如果它猜对了你的输入,它就赢了,如果猜对了,玩家就赢了。第一个赢了25场,赢了整场比赛使用Java程序获取ArrayIndexOutOfBounds错误,该程序试图根据以前的决定猜测下一个选择(正面或反面),java,Java,我正在制作一个程序,试图根据之前的决定猜测你是选择正面(h)还是反面(t)。程序在前3次猜测“h”,然后查找玩家的最后两个选择,通过前面的选择找到相同的决策组合,并计算哪个决策(h或t)最多次遵循相同的组合,然后选择该决策作为猜测。如果它猜对了你的输入,它就赢了,如果猜对了,玩家就赢了。第一个赢了25场,赢了整场比赛 while (list.size() > 3 && index < list.size()) {
while (list.size() > 3 && index < list.size()) {
if (list.get(index - 2).equals(list.get(secondToLast))
&& list.get(index - 1).equals(list.get(last))) {
String nextGuess = list.get(index);
if (nextGuess.equals("t")) {
t++;
} else {
h++;
}
}
index++;
}
该程序在前3次猜测中运行良好,但当它进入第二个while循环时,会给出“线程中的异常”main“java.lang.ArrayIndexOutOfBoundsException:-2”
while (list.size() > 3 && index < list.size()) {
if (list.get(index - 2).equals(list.get(secondToLast))
&& list.get(index - 1).equals(list.get(last))) {
String nextGuess = list.get(index);
if (nextGuess.equals("t")) {
t++;
} else {
h++;
}
}
index++;
}
这些行有错误:
while (list.size() > 3 && index < list.size()) {
if (list.get(index - 2).equals(list.get(secondToLast))
&& list.get(index - 1).equals(list.get(last))) {
String nextGuess = list.get(index);
if (nextGuess.equals("t")) {
t++;
} else {
h++;
}
}
index++;
}
ArrayList<String> list = new ArrayList<>();// here list is empty and its size is 0
int last = (list.size() - 1);// here last is 0 - 1 = -1
int secondToLast = (list.size() - 2);// here secondToLast is 0 - 2 = -2
更改此行:
while(list.size()>3&&index
while (list.size() > 3 && index < list.size()) {
if (list.get(index - 2).equals(list.get(secondToLast))
&& list.get(index - 1).equals(list.get(last))) {
String nextGuess = list.get(index);
if (nextGuess.equals("t")) {
t++;
} else {
h++;
}
}
index++;
}
为此:
while (list.size() > 3 && index < list.size()) {
if (list.get(index - 2).equals(list.get(secondToLast))
&& list.get(index - 1).equals(list.get(last))) {
String nextGuess = list.get(index);
if (nextGuess.equals("t")) {
t++;
} else {
h++;
}
}
index++;
}
while (list.size() > 3 && index >= 2 && index < list.size())
int secondToLast = list.size() - 2 >= 0 ? list.size() - 2 : 0;
把这些放在while循环中。它会起作用。:你明白ArrayIndexOutOfBounds是什么意思吗?@Thorbjørn Ravn Andersen是的,例如,当你试图获取一个太高(值后面没有指定列表对象)或低于0的值时,它不会出现。是的,这是最干净的方法。谢谢:D
while (list.size() > 3 && index < list.size()) {
if (list.get(index - 2).equals(list.get(secondToLast))
&& list.get(index - 1).equals(list.get(last))) {
String nextGuess = list.get(index);
if (nextGuess.equals("t")) {
t++;
} else {
h++;
}
}
index++;
}