Question: Trace the following program step by step, to find the program modification of the names array list when user enter ahmed. Write the output when
Trace the following program step by step, to find the program modification of the names array list when user enter ahmed. Write the output when the user enters ahemd and when enters salem.
import java.util.Scanner;
public class Student_ArrayList {
public static void main(String[] args) {
java.util.ArrayList
names.add("Eman");
names.add("Rwan");
names.add("Ahmed");
names.add("Kaled");
System.out.print("Names: ");
System.out.println(names);
Scanner in = new Scanner(System.in);
System.out.print("Enter a name: ");
String x = in.next();
boolean removed_flag= false;
for (int i = 0; i < names.size(); i++)
{
if (i < names.size()) {
String pName = names.get(i);
if (pName.equalsIgnoreCase(x)) {
names.remove(i);
removed_flag= true;
}
}
}
if (removed_flag==false) {
names.add(x);
}
System.out.print("Updated names: ");
System.out.println(names);
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
