分隔的整数列表

编程入门 行业动态 更新时间:2024-10-21 02:50:10
本文介绍了分隔的整数列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是原始提示:

编写程序,在命令行上从用户处获取用逗号分隔的整数字符串(例如"4,8,16,32,…"),然后将字符串转换为整数的ArrayList(使用包装器类)),每个元素依次包含输入整数之一.最后,使用for循环将整数输出到命令行,每个整数都放在单独的行上.

Write program that gets a comma-delimited String of integers (e.g. "4,8,16,32,…") from the user at the command line and then converts the String to an ArrayList of Integers (using the wrapper class) with each element containing one of the input integers in sequence. Finally, use a for loop to output the integers to the command line, each on a separate line.

import java.util.Scanner; import java.util.ArrayList; public class Parser { public static void main(String[] args) { Scanner scnr = new Scanner(System.in); ArrayList<String> myInts = new ArrayList<String>(); String integers = ""; System.out.print("Enter a list of delimited integers: "); integers = scnr.nextLine(); for (int i = 0; i < myInts.size(); i++) { integers = myInts.get(i); myInts.add(integers); System.out.println(myInts); } } }

我能够将其放置到接受带分隔符的整数列表的位置,但是我卡在转换块和for循环上,特别是将每个数字打印到单独的行上.

I was able to get it to where it accepts the list of delimited integers, but I'm stuck on the converting piece of it and the for loop, specifically printing each number to a separate line.

推荐答案

转换此字符串的最简单方法是根据逗号将其拆分,然后将 Integer.valueOf 应用于每个元素:

The easiest way to convert this string would be to split it according to the comma and apply Integer.valueOf to each element:

List<Integer> converted = Arrays.stream(integers.split(",")) .map(Integer::valueOf) .collect(Collectors.toList());

打印它们,假设您必须使用 for 循环,就意味着循环遍历它们并单独打印每个:

Printing them, assuming you have to use a for loop, would just mean looping over them and printing each one individually:

for (Integer i : converted) { System.out.println(i); }

如果您不必绝对使用 for 循环,那么即使不存储到临时列表,也可以使用流更优雅地完成此操作:

If you don't absolutely have to use a for loop, this could also be done much more elegantly with streams, even without storing to a temporary list:

Arrays.stream(integers.split(",")) .map(Integer::valueOf) .forEach(System.out::println);

更多推荐

分隔的整数列表

本文发布于:2023-11-30 09:40:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649531.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   列表

发布评论

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

>www.elefans.com

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