In: Computer Science
Write Java code to generate 100 random integers ranging from 0..9, inserting each element into an ArrayList. Then search for the first instance of the number 3, print the position, and then remove it from the list.
import java.util.ArrayList; import java.util.Random; public class RandomArrayList { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<>(); Random rand = new Random(); for(int i = 0;i<100;i++){ list.add(rand.nextInt(10)); } System.out.println("ArrayList: "+list); int index = list.indexOf(3); if(index!=-1) { list.remove(index); System.out.println("Position of the value 3 is "+index); } else{ System.out.println("3 not found"); } System.out.println("ArrayList after removal of 3: "+list); } }
ArrayList: [9, 1, 7, 8, 7, 5, 4, 0, 4, 2, 4, 8, 0, 2, 7, 9, 9, 0, 5, 4, 4, 5, 4, 2, 6, 6, 1, 4, 1, 5, 3, 2, 9, 4, 3, 4, 4, 4, 6, 2, 7, 6, 8, 7, 5, 2, 4, 3, 0, 9, 5, 5, 0, 9, 3, 0, 2, 7, 6, 3, 8, 9, 2, 1, 6, 6, 2, 7, 3, 0, 0, 7, 3, 5, 3, 3, 6, 2, 5, 2, 3, 9, 3, 1, 6, 1, 6, 8, 2, 2, 3, 6, 6, 7, 9, 7, 5, 1, 0, 7] Position of the value 3 is 30 ArrayList after removal of 3: [9, 1, 7, 8, 7, 5, 4, 0, 4, 2, 4, 8, 0, 2, 7, 9, 9, 0, 5, 4, 4, 5, 4, 2, 6, 6, 1, 4, 1, 5, 2, 9, 4, 3, 4, 4, 4, 6, 2, 7, 6, 8, 7, 5, 2, 4, 3, 0, 9, 5, 5, 0, 9, 3, 0, 2, 7, 6, 3, 8, 9, 2, 1, 6, 6, 2, 7, 3, 0, 0, 7, 3, 5, 3, 3, 6, 2, 5, 2, 3, 9, 3, 1, 6, 1, 6, 8, 2, 2, 3, 6, 6, 7, 9, 7, 5, 1, 0, 7]