Trace the following program step by step, to find the program modification of th
ID: 3712808 • Letter: T
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 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<String> names = new java.util.ArrayList<String>();
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);
}
}
Explanation / Answer
Following is the answer:
When user enters the name then program finds the name in list and is name is found then program delete the name and displays the remaining output, and if name is not found in the list then program adds the name in arraylist and then prints the list.
1) When enters ahmed output is:
Names: [Eman, Rwan, Ahmed, Kaled]
Enter a name: ahmed
Updated names: [Eman, Rwan, Kaled]
2) When enter salem then output is:
Names: [Eman, Rwan, Ahmed, Kaled]
Enter a name: salem
Updated names: [Eman, Rwan, Ahmed, Kaled, salem]
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.