Failed to fix java.lang.ArrayIndexOutOfBoundsException

I hope I can formulate my question well, as I am from Germany ... :)

I have a very simple Java program, but when I run it, I get a java.lang.ArrayIndexOutOfBoundsException error. I was looking for a problem, but I can not 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 as follows:

  • Create a new c code with the code "0 ~ A".
  • Create a new object o with code c
  • Make "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 do not understand why I can not use "activeStepSeq [0]" ...

Hope you can help me, Marvin greetings

+4
2

, String.split , . .

Try

this.code.split("\\.")
+6

"" () java, . split, split , :

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

Source: https://habr.com/ru/post/1568625/


All Articles