Getting ArrayIndexOutOfBounds error with Java program that tries to guess your next choice (heads or tails) based on previous decisions : <p>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.</p>

<p>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"</p>

<pre><code>import java.util.ArrayList;
import java.util.Scanner;

public class Guesser {

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        ArrayList&lt;String&gt; list = new ArrayList&lt;&gt;();

        int last = (list.size() - 1);
        int secondToLast = (list.size() - 2);

        int index = 2;
        int wins = 0;

        int h = 0;
        int t = 0;

        while (wins &lt; 25 &amp;&amp; list.size() - wins &lt; 25) {
            System.out.println("Type h or t: ");
            String letter = reader.nextLine();
            list.add(letter);
            String guess = "h";
</code></pre>

<p>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):           </p>

<pre><code>            while (list.size() &gt; 3 &amp;&amp; index &lt; list.size()) {

                if (list.get(index - 2).equals(list.get(secondToLast)) 
                    &amp;&amp; list.get(index - 1).equals(list.get(last))) {

                    String nextGuess = list.get(index); 
                    if (nextGuess.equals("t")) {
                        t++;
                    } else {
                        h++;
                    }

                }
                index++;

            }
</code></pre>

<p>Everything below here works:</p>

<pre><code>            if (t &gt; 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("");
        } 

    }
}
</code></pre>
