0

The code below is giving problems, I just need to turn a letter from a string into a character, and when I run my testing, I keep getting an error when the code gets to char c = t.charAt(0); The exact error message is:

java.lang.StringIndexOutOfBoundsException: String index out of range: 0

I cannot get it to just turn the string letter into a char. Any tips would be greatly appreciated.

String[] zombies;
int num = 0;
Vector<Zombie> practice = new Vector<Zombie>();
String zombieString = "SZI1";
zombies = zombieString.split("");

for (String t : zombies) {
    if (isNumeric(t)) {
        int multiplier = Integer.parseInt(t);
        String extraZombie = zombies[num - 1];
        char x = extraZombie.charAt(0);
        for (int i = 0; i <= multiplier; i++) {
            Zombie zombie = Zombie.makeZombie(x);
            practice.add(zombie);
        }
    } else {
        char c = t.charAt(0);
        //Zombie zombie = Zombie.makeZombie(c);
        //practice.add(zombie);
        num++;
    }
}
Perception
  • 79,279
  • 19
  • 185
  • 195

3 Answers3

3

Your split("") returns an empty string, and if you call charAt(0) on an empty string it will give this error.

To solve this you could replace the split("") operation with toCharArray(), this will directly generate an array of chars:

char[] zombies = zombieString.toCharArray();
Matt
  • 1,148
  • 10
  • 15
0

Since it says "string index out of range 0", then your string has no characters in it. Might have something to do with the fact that you're telling String.split() to split on an empty string, when it needs a string delimiter on which to split.

arcy
  • 12,845
  • 12
  • 58
  • 103
0

Quoted:
https://stackoverflow.com/a/5235439/2214674

"SZI1".toCharArray()
    But if you need strings

    "SZI1".split("")
    Edit: which will return an empty first value (extra empty String => [, S, Z, I,1].).
Community
  • 1
  • 1
kinkajou
  • 3,664
  • 25
  • 75
  • 128