Reputation: 137
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?
Upvotes: 0
Views: 3151
Reputation: 425033
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.
Upvotes: 1
Reputation: 20536
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.
Upvotes: 2
Reputation: 2676
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);
}
Upvotes: 3