0

How could I split the numbers in the string "542" into individual digits? On my desktop I can split the numbers using String.split("") and it works fine. But when run on Android, I get a NumberFormatException: Invalid int: "". This is my code:

public void render(int n, SpriteBatch batch) {
    String[] numbers = String.valueOf(n).split("");
    for(int i = 0; i < numbers.length; i++) 
        batch.draw(Assets.numbers[0][Integer.valueOf(numbers[i])], pos.x + (50 * i), pos.y);
}

Is there an alternative way?

user3316633
  • 137
  • 5
  • 13

3 Answers3

3

You can use String.charAt, that will give you a Character. Removing '0' will give you a value from 0 to 9.

public void render(int n, SpriteBatch batch) {
    String string = Integer.toString(n);
    for(int i = 0; i < string.length(); ++i) 
        batch.draw(Assets.numbers[0][string.charAt(i) - '0'],
                   pos.x + (50 * i), pos.y);
}
Nicolas Defranoux
  • 2,646
  • 1
  • 10
  • 13
2

Your use of String.split("") will always leave the first index empty (that is, the String: ""). This is why you are getting NumberFormatException: Invalid int: "" when trying to run Integer.valueOf(numbers[0]).

Suggest using string.charAt(index) to iterate over the characters in String.valueOf(n) instead.

Halvor Holsten Strand
  • 19,829
  • 17
  • 83
  • 99
  • 1
    "String.split("") will always leave the first index empty", not always, [at least not from Java 8](http://stackoverflow.com/questions/22718744/why-does-split-in-java-8-sometimes-removes-empty-strings-if-they-are-at-start-of). – Pshemo Jun 22 '14 at 23:04
1

Splitting on "" will cause the first element of the resulting array to be a blank, because the blank regex matches everywhere, including start of input.

You need to split after every character:

String[] digits = str.split("(?<=.)");

This regex is a look behind that assets there is a character before the match. Look behinds are non-consuming, so you don't lose any input making the split.

Bohemian
  • 412,405
  • 93
  • 575
  • 722