拆分字符串并将其转换为 int [英] Splitting and converting String to int
问题描述
我的代码有问题.我读了几个文本文件的数字.例如:文本文件.txt
I have a problem with my code. I read a couple of numbers of a text-file. For example: Textfile.txt
1, 21, 333
使用以下代码,我想将数字从 String 拆分并转换为 int.
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);
}
我在控制台中得到结果(int):
I get the result in my console (int):
1 3 9
我看到数字 3 是 2 + 1 的结果,数字 9 是 3 + 3 + 3 的结果.我该怎么做才能在我的控制台 (int) 中收到以下结果?
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
/ 我只允许使用 Java.lang 和 Java.IO
/ I am only allowed to use Java.lang and Java.IO
推荐答案
这是一个使用 Java 8 流的解决方案:
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());
<小时>
或者,使用循环,只需使用 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);
}
这篇关于拆分字符串并将其转换为 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!