Splitting and converting String to int

后端 未结 5 1619
再見小時候
再見小時候 2021-01-12 06:23

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 wan

5条回答
  •  我在风中等你
    2021-01-12 06:54

    A couple of problems:

    1. factor should be multiplied by 10 in every loop
    2. answer and factor should be re-initialized between the numbers you're parsing:

    String line = "1,21,333";
    for (String retval : line.split(",")) {
        int answer = 0;
        int factor = 1;
        for (int j = retval.length() - 1; j >= 0; j--) {
            answer = answer + (retval.charAt(j) - '0') * factor;
            factor *= 10;
        }
        System.out.println(answer);
        answer = (answer - answer);
    }
    

    OUTPUT

    1
    21
    333
    

提交回复
热议问题