35.6k views
5 votes
Write a program to initialize an ArrayList of Strings and insert ten words. Then, using Math.random, print two different Strings from the list. The two string must be different, you will need to check that before printing them. Paste your program into the code-runner box below and press run. For this activity, the words you use do not matter, but the values in the ArrayList should not contain any whitespace. Every time you call main, it should print a different pair of values from the list. Write your code in a class named Lesson_12_FastStart

User Ehabd
by
4.7k points

1 Answer

3 votes

Answer:

  1. import java.util.ArrayList;
  2. import java.util.Random;
  3. public class Main {
  4. public static void main(String[] args) {
  5. ArrayList<String> arrStr = new ArrayList<String>(10);
  6. arrStr.add("Apple");
  7. arrStr.add("Banana");
  8. arrStr.add("Cat");
  9. arrStr.add("Dog");
  10. arrStr.add("Elephant");
  11. arrStr.add("Fox");
  12. arrStr.add("Good");
  13. arrStr.add("Home");
  14. arrStr.add("Icecream");
  15. arrStr.add("Jaspel");
  16. Random rand = new Random();
  17. int n1 = rand.nextInt(10);
  18. int n2 = rand.nextInt(10);
  19. while(n1 == n2){
  20. n2 = rand.nextInt(10);
  21. }
  22. System.out.println(arrStr.get(n1));
  23. System.out.println(arrStr.get(n2));
  24. }
  25. }

Step-by-step explanation:

The solution code is written in Java.

Firstly, create an array list and set 10 strings to the array list (Line 7-17).

Use random nextInt method to generate a number between 0-9 as index (Line 19-21).

While the first random number and the second random number is equal, find a new random random (Line 22-24).

At last print out the first random string and second random string using the n1 & n2 as index to extract the string items from the array list (Line 26-27).

User Rymnel
by
4.9k points