Write a complete Java program called Parser that uses methods to 1. get a comma-
ID: 3815962 • 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. I already asked this but it wasn't helpful because it didn't use different methods such as one to get the input, another one to convert the String to an ArrayList of integers, and another method to print each integer on a separate line.
Explanation / Answer
Parser.java
package com.examples;
import java.util.ArrayList;
public class Parser {
public static void main(String[] args) {
String s = getInput();
ArrayList<Integer> list = getArrayList(s);
printNumbers(list);
}
public static String getInput() {
java.util.Scanner in = new java.util.Scanner(System.in);
System.out.println("Please enter input string with comma delimiter...");
String s = in.nextLine();
return s;
}
public static ArrayList<Integer> getArrayList(String s){
String values[] = s.split(",");
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i=0; i<values.length; i++){
list.add(Integer.parseInt(values[i].trim()));
}
return list;
}
public static void printNumbers(ArrayList<Integer> list){
System.out.println("Output is:");
for(int i=0; i<list.size(); i++)
System.out.println(list.get(i));
}
}
Output:
Please enter input string with comma delimiter...
4, 8, 16, 32
Output is:
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.