I have a string. I split and store it as a char
array . I am trying to convert it using Integer.parseInt
and I get an error. How do I convert String to int?
Here's my code:
String tab[]= null;
tab=pesel.split("");
int temp=0;
for(String tab1 : tab)
{
temp=temp+3*Integer.parseInt(tab1); //error
}
Assuming you have a string of digits (e.g. "123"
), you can use toCharArray()
instead:
for (char c : pesel.toCharArray()) {
temp += 3 * (c - '0');
}
This avoids Integer.parseInt()
altogether. If you want to ensure that each character is a digit, you can use Character.isDigit()
.
Your error is because str.split("")
contains a leading empty string in the array:
System.out.println(Arrays.toString("123".split("")));
[, 1, 2, 3]
Now, there is a trick using negative lookaheads to avoid that:
System.out.println(Arrays.toString("123".split("(?!^)")));
[1, 2, 3]
Although, in any case, I would prefer the approach shown above.