简体   繁体   中英

Comma-Delimited String of Integers

This is the original prompt:

I need to write a program that gets a comma-delimited String of integers (eg “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.

This is the code that I have so far:

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

    System.out.println(integers);

}
}

I am confused on where to go with the rest of this program. If someone could help explain to me what I need to do, that would be much appreciated!

As Matthew and Marc pointed out you have to first split the string into tokens and then parse each token to transform them into Integers.

You could try it with something like this:

    String stringOfInts = "1,2,3,4,5";
    List<Integer> integers = new ArrayList<>();
    String[] splittedStringOfInts = stringOfInts.split(",");
    for(String strInt : splittedStringOfInts) {
        integers.add(Integer.parseInt(strInt));
    }

    // do something with integers

In the split() method you define how to split the string into tokens. In your case it's simply the comma (,) sign.

Hope this helps.

Regards Patrick

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM