I have a problem with my code. I read a couple of numbers of a text-file. For example: Textfile.txt
1, 21, 333
With my following code I want to split and convert the numbers from String to int.
int answer = 0;
int factor = 1;
// Splitting and deleting the "," AND converting String to int.
for (String retval : line.split(",")) {
for (int j = retval.length() - 1; j >= 0; j--) {
answer = answer + (retval.charAt(j) - '0') * factor;
factor *= 1;
}
System.out.println(answer);
answer = (answer - answer);
}
I get the result in my console (int):
1 3 9
I see that the number 3 is a result of 2 + 1, and the number 9 is a result of 3 + 3 + 3. What can I do, to receive the following result in my console (int)?
1 21 333
/EDIT: I am only allowed to use Java.lang and Java.IO
You can use
Integer.valueOf(retval)
orInteger.parseInt(retval)
Well, you could make answer a string, and cast it to an integer after the for loop.
A couple of problems:
factor
should be multiplied by 10 in every loopanswer
andfactor
should be re-initialized between the numbers you're parsing:OUTPUT
For folks who come here from a search, this function takes a separated values string and delimiter string and returns an integer array of extracted values.
Here's a solution using Java 8 streams:
Alternatively, with a loop, just use
parseInt
:If you really want to reinvent the wheel, you can do that, too: