Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to fix java.lang.ArrayIndexOutOfBoundsException

Tags:

java

arrays

I hope I'm able to formulate my question well since I'm from Germany... :)

I got a very basic java programm but when I start it I get a java.lang.ArrayIndexOutOfBoundsException error. I searched for the problem but I'm unable to find it:

Code.java

public class Code {
    private String code;
    private int nextStep;

    public Code() {
        nextStep = 0;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public void setNextStep(int lastStep) {
        this.nextStep = lastStep;
    }

    public String getActiveStepSeq() {
        String[] activeStepSeq = this.code.split(".");
        return(activeStepSeq[0]);
    }
}

Object.java

public class Being {
    public Code code;
    private String activeStepSeq;
    private String activeAction;

    public String I0;
    public String O0;
    public String S0;

    public Object(Code code) {
        this.code = code;
    }

    public void parseStep() {
        this.activeStepSeq = this.code.getActiveStepSeq();
        this.code.setNextStep(Integer.parseInt(this.activeStepSeq.split("~")[0]));
        this.activeAction = this.activeStepSeq.split("~")[1];
        switch(this.activeAction) {
        case("A"):
            this.O0 = this.I0;
            break;
        }
    }
}

Main.java

public class Main {
    public static void main(String[] args) {
        Code c = new Code();
        c.setCode("0~A.");
        Object o = new Object(c);
        o.I0 = "Test";
        o.parseStep();
        System.out.println(o.O0);
    }
}

It should work like that:

  • Create new Code c with the code "0~A."
  • Create new Object o with the Code c
  • Do "parseStep" which gets the String "0~A"
  • Set nextStep to 0 and set o.O0 to o.I0

But now I get the following error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at Code.getActiveStepSeq(Code.java:19)
    at Object.parseStep(Object.java:15)
    at Main.main(Main.java:7)

I don't get why I can't use "activeStepSeq[0]"...

I hope you can help me, greetings Marvin

like image 257
Marvin Avatar asked Feb 12 '23 07:02

Marvin


1 Answers

Note that String.split takes a regular expression as argument, and . has a special meaning in regular expressions.

Try

this.code.split("\\.")
like image 86
aioobe Avatar answered Feb 13 '23 20:02

aioobe