Search code examples
javaautomata

I dont understand why i get an ArrayIndexOutOfBoundsException 2 error


I am trying to make a program that does cellular automata in 1D. For that, i need to read three variables from a single line. one of the variables, "L", determines the array length of "currentGeneration". However I get the ArrayIndexOut... error. I think this has to do with the dimension of my array and the variable L.

public class Cellulitissss {
    int L;
    Scanner sc = new Scanner(System.in);
    Boolean[] currentGeneration;
    String automaton;
    int G;
    String X;
    String Z;

    public void readGeneral() {

        String[] values = new String[2];
        for (int i = 0; i < 3; i++) {
            values[i] = sc.next();
        }
        automaton = values[0];
        X = values[1];
        Z = values[2];
        L = Integer.parseInt(X);
        G = Integer.parseInt(Z);
        currentGeneration = new Boolean[L + 1];
    }
}

Solution

  • You have tried to access values [2] which is wrong because array index starts from 0 so an array storing 2 values will store them at locations a[0] and a[1] if a is your array name. So trying to access a[2] will give an array index out of bounds exception