In: Computer Science
Write a java program:
Write a nested loop program creating an array list of three positions. The first loop terminates with a sentinel value of which user is prompted for input to continue of quit. Inside loop to enter in each position a prompted input of person's first name. After the inside loop, edit the second array location making its value "Boston". Print the array's contents.
//JAVA CODE
import java.util.ArrayList;
import java.util.Scanner;
class MyArrayList
{
public static void main(String args[])
{
//create an Array List of size 3
ArrayList<String> names=new ArrayList<String>(3);
//create a scanner object
Scanner sc=new Scanner(System.in);
//temporary variable to store first name
String s="";
//stores the user choice to continue or not
char choice;
//outer loop
while(true)
{
//inner loop
for(int i=0;i<3;i++)
{
System.out.println("\n Enter person first name :");
//accepts a name from user
s=sc.next();
//adding to array list
names.add(s);
}
//display the array list
System.out.println("Actual List :"+ names);
//replace the element at second position as "Boston"
names.set(1,"Boston");
//display the array list
System.out.println("Actual List :"+ names);
System.out.println("\n Do you want to continue (y/n) :");
//accept the user choice to continue or not
choice=sc.next().toLowerCase().charAt(0);
//clear the list
names.clear();
if(choice=='n')
break;
}
}
}
OUTPUT