Write a complete Java program called Parser that uses methods to 1. get a comma-
ID: 3814958 • Letter: W
Question
Write a complete Java program called Parser that uses methods to 1. get 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, and 2. print the integers to the command line, using a for loop, so that each integer is on a separate line. Note: Use the split method to split on a comma and a space. Then, go through the "numbers as strings" array and convert those numbers to Integers (the wrapper) class and load them into an array list for printing.
Explanation / Answer
HI, Please find my implementation.
import java.util.ArrayList;
public class Parser {
public static void main(String[] args) {
if(args == null){
System.out.println("Please pass comma-delimited String of integers from command line");
return;
}
// splitting string by comma
String strArr[] = args[0].split(",");
ArrayList<Integer> list = new ArrayList<>();
// converting each string into integer and adding in array list
for(String str : strArr)
list.add(Integer.parseInt(str.trim()));
// printing array list
for(Integer i : list)
System.out.println(i);
}
}
/*
Sample run:
4
8
16
32
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.