拆分字符串并将其转换为 int

编程入门 行业动态 更新时间:2024-10-25 16:25:26
本文介绍了拆分字符串并将其转换为 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

本文发布于:2023-11-10 03:10:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574189.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   字符串   并将其   int

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!