4

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

1
  • 1
    insert this at line number 19 on code class return this.code.split("\\.")[0]; Dec 22, 2014 at 13:46

2 Answers 2

6

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

Try

this.code.split("\\.")
1
  • Thanks! That was the problem :)
    – Marvin
    Dec 22, 2014 at 13:35
2

"." (dot) is a special character in java used in regex. You should escape it in split method as split takes regex like:

String[] activeStepSeq = this.code.split("\\.");
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.