我正在制作一个程序,试图根据之前的决定猜测您是要选择正面(h)还是反面(t)。程序在前 3 次猜测“h”,然后查找玩家的最后两个选择,遍历之前的选择以找到相同的决策组合并计算哪个决策(h 或 t)遵循相同组合最多次数,然后根据猜测选择组合。如果它猜对了你的输入,它就赢了,否则玩家就赢了。第一个获得25胜,赢得整场比赛。
该程序对前 3 次猜测工作正常,但当它进入第二个 while 循环时,它给出“线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: -2”
import java.util.ArrayList;
import java.util.Scanner;
public class Guesser {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
ArrayList<String> list = new ArrayList<>();
int last = (list.size() - 1);
int secondToLast = (list.size() - 2);
int index = 2;
int wins = 0;
int h = 0;
int t = 0;
while (wins < 25 && list.size() - wins < 25) {
System.out.println("Type h or t: ");
String letter = reader.nextLine();
list.add(letter);
String guess = "h";
当程序进入此文本下方的 while 循环时,它停止工作(程序应该在此处尝试将最后两个决策与之前的所有决策进行比较,以尝试找到相同的决策组合并找出哪个决策(h 或 t)大部分时间遵循组合):
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++;
}
下面的一切都有效:
if (t > h) {
guess = "t";
}
System.out.println("You typed " + letter + ", I guessed " + guess +".");
if (guess.equals(letter)) {
wins++;
}
System.out.println("Computer wins: " + wins);
System.out.println("Player wins: " + (list.size() - wins));
System.out.println("");
}
}
}
蝴蝶刀刀
跃然一笑
相关分类