Splitting and converting String to int

2020-03-17 03:43发布

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

5条回答
唯我独甜
2楼-- · 2020-03-17 04:14

You can use Integer.valueOf(retval) or Integer.parseInt(retval)

查看更多
ら.Afraid
3楼-- · 2020-03-17 04:15

Well, you could make answer a string, and cast it to an integer after the for loop.

查看更多
再贱就再见
4楼-- · 2020-03-17 04:16

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
查看更多
贼婆χ
5楼-- · 2020-03-17 04:24

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.

int[] parseStringArr( String str, String delim ) {
    String[] strArr = str.trim().split(delim);
    int[] intArr = new int[strArr.length];
    for (int i = 0; i < strArr.length; i++) {
        String num = strArr[i].trim();
        intArr[i] = Integer.parseInt(num);
    }
    return intArr;
}
查看更多
够拽才男人
6楼-- · 2020-03-17 04:28

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);
}
查看更多
登录 后发表回答