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

Numbers = [45, 61, 44. 88, 91, 13, 65, 50. 98, 11] # This structure is called a

ID: 3577455 • Letter: N

Question

Numbers = [45, 61, 44. 88, 91, 13, 65, 50. 98, 11] # This structure is called a list Define a counter variable When setting its value remember that the index value of the first element in a list is zero Ask the user to enter a number to search for Your code should handle numbers both present in the list and absent from the list You wish to determine whether a number is present in the list and, if so, where it is located. To search through the list, use the form: for in # variable.Name will hold each value in the list, one after another

Explanation / Answer

import java.util.ArrayList;

public class SearchAnElementInArrayListExample {

public static void main(String[] args) {

  
ArrayList arrayList = new ArrayList();


arrayList.add("45");
arrayList.add("61");
arrayList.add("44");
arrayList.add("88");
arrayList.add("91");
arrayList.add("13");
arrayList.add("68");
arrayList.add("50");
arrayList.add("98");
arrayList.add("11");

boolean blnFound = arrayList.contains("2");
System.out.println("Does arrayList contain 2 ? " + blnFound);


int index = arrayList.indexOf("4");
if(index == -1)
System.out.println("ArrayList does not contain 4");
else
System.out.println("ArrayList contains 4 at index :" + index);


int lastIndex = arrayList.lastIndexOf("1");
if(lastIndex == -1)
System.out.println("ArrayList does not contain 1");
else
System.out.println("Last occurrence of 1 in ArrayList is at index :"
+ lastIndex);

}
}