Java – split and convert string to int

There is something wrong with my code I read several text files For example:

1,21,333

Using my following code, I want to split and convert 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 got the result in my console (int):

1 3 9

I see that the number 3 is the result of 2 1 and the number 9 is the result of 3 3 What should I do to receive the following results in my console (int)?

1 21 333

/Editor: I only allow Java Lang and Java IO

Solution

This is a solution using java 8 streaming:

String line = "1,33";
List<Integer> ints = Arrays.stream(line.split(","))
        .map(Integer::parseInt)
        .collect(Collectors.toList());

Alternatively, to use a loop, simply use parseInt:

String line = "1,33";
for (String s : line.split(",")) {
    System.out.println(Integer.parseInt(s));
}

If you really want to reinvent the wheel, you can do the same:

String line = "1,")) {
    char[] chars = s.tocharArray();
    int sum = 0;
    for (int i = 0; i < chars.length; i++) {
        sum += (chars[chars.length - i - 1] - '0') * Math.pow(10,i);
    }
    System.out.println(sum);
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>