AgentTadpole

Answers - ArrayLists

Jan 16th, 2014
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.68 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.Random;
  3.  
  4. public class Loop {
  5.     public static void main(String[] args) {
  6.         // Create ArrayList and Random
  7.         ArrayList<String> list = new ArrayList<String>();
  8.         Random rand = new Random();
  9.        
  10.         // Add values to ArrayList list
  11.         list.add("hi");
  12.         list.add("World");
  13.         list.add("Greetings");
  14.         list.add("Jupiter");
  15.         list.add("Riddle");
  16.        
  17.         // Loop 5 times
  18.         for(int i=0;i<5;i++) {
  19.             // Randomly select a number based on the number of iterations the loop has run through
  20.             int n = rand.nextInt(5-i);
  21.             // Print that index to console and remove from the ArrayList list
  22.             System.out.println(list.get(n));
  23.             list.remove(n);
  24.         }
  25.     }
  26. }
Advertisement
Add Comment
Please, Sign In to add comment