Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
134 views
Welcome To Ask or Share your Answers For Others

1 Answer

Here's a solution using Java 8 streams:

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

Alternatively, with a loop, just use parseInt:

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

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

String line = "1,21,33";
for (String s : line.split(",")) {
    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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...