Delimited List of Integers

*爱你&永不变心* 提交于 2021-01-28 17:56:42

问题


This is the original prompt:

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);
        }
    }
}

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.


回答1:


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());

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);
}

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);



回答2:


First, you can convert the input string to String[], by using the split method: input.split(","). This will give you an array where the elements are strings which were separated by ",".

And then, to convert a String to an Integer wrapper, you can use:

  1. Integer i = Integer.valueOf(str);
  2. Integer i = Integer.parseInt(str)



回答3:


myInts is empty, your data is in integers.
I suggest that you search about the fonction : split (from String)



来源:https://stackoverflow.com/questions/36161343/delimited-list-of-integers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!