I'm making a program that tries to guess if you're going to choose heads(h) or tails(t) based on previous decisions. The program guesses "h" for the first 3 times and after that it looks for the last two choices of the player, goes through the previous choices to find the same combo of decisions and calculates which decision (h or t) has followed this same combo the most times and then chooses that as it's guess. If it guesses your input right it gets a win, if it doesn't the player gets a win. First one to get 25 wins, wins the whole game.
The program works fine for the first 3 guesses but when it enters the second while-loop it gives "Exception in thread "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";
When the program enters this while-loop below this text, it stops working (this is where the program is supposed to try and compare the last two decisions with all of the previous decisions to try and find same combo of decisions and to figure out which decision (h or t) follows the combo most of the time):
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++;
}
Everything below here works:
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("");
}
}
}