Write a complete Java program called \"Parser\" (without the quotation marks) th
ID: 3703082 • Letter: W
Question
Write a complete Java program called "Parser" (without the quotation marks) that
Uses a method to ask the user for a comma-and-space-delimited String of integers (e.g., "4, 8, 16, 32")
Uses a method to convert the user input to an ArrayList of integers (using the wrapper class) with each element of the ArrayList containing one of the the integers entered by the user
Uses a method containing a for loop to print each of the integers on a separate line.
EXAMPLE: If the user enters the String "-30, 1002, 17, 8073, 2" your program should print those numbers as follows.
Explanation / Answer
Parser.java
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...
-30, 1002, 17, 8073, 2
Output is:
-30
1002
17
8073
2
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.