问题
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:
Integer i = Integer.valueOf(str);
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