Write a Java code snippet to do the following: Declare and instantiate an ArrayL
ID: 3801565 • Letter: W
Question
Write a Java code snippet to do the following: Declare and instantiate an ArrayList of Strings Use a do-while loop to prompt for and read the Strings (lines of text) from the user at the command line until they enter a sentinel value. Use a for loop to step through the ArrayList and concatenate a line number to the beginning of each line eg: This is change to 1 This is The first day change to 2 The first day and so on.. Finally, use a for loop to output theStrings (numbered lines) to the command lineExplanation / Answer
import java.util.ArrayList;
import java.util.Scanner;
public class Assignment {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList<>();
Scanner sc = new Scanner(System.in);
//Reading Input from user
do{
System.out.println("Enter Line of Text ( zzz To Stop) :");
String line = sc.nextLine();
if(line.equalsIgnoreCase("zzz"))
break;
arrayList.add(line);
}while(true);
sc.close();
//adding line number
for(int i=0;i<arrayList.size();i++){
String line = arrayList.remove(i);
line = ""+(i+1)+" "+line;
arrayList.add(i, line);
}
// printing on command line
System.out.println("===================================");
for(int i=0;i<arrayList.size();i++){
System.out.println(""+arrayList.get(i));
}
System.out.println("===================================");
}
}
//================================== OUTPUT ================////
Enter Line of Text ( zzz To Stop) :
This is
Enter Line of Text ( zzz To Stop) :
The first day
Enter Line of Text ( zzz To Stop) :
zzz
===============
1 This is
2 The first day
================
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.