Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

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 line

Explanation / 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

================

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote