Ask Question

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

+2
Answers (1)
  1. 20 January, 23:33
    0
    import java. util. ArrayList; import java. util. Random; public class Main { public static void main (String[] args) { ArrayList arrStr = new ArrayList (10); arrStr. add ("Apple"); arrStr. add ("Banana"); arrStr. add ("Cat"); arrStr. add ("Dog"); arrStr. add ("Elephant"); arrStr. add ("Fox"); arrStr. add ("Good"); arrStr. add ("Home"); arrStr. add ("Icecream"); arrStr. add ("Jaspel"); Random rand = new Random (); int n1 = rand. nextInt (10); int n2 = rand. nextInt (10); while (n1 = = n2) { n2 = rand. nextInt (10); } System. out. println (arrStr. get (n1)); System. out. println (arrStr. get (n2)); } }

    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).
Know the Answer?
Not Sure About the Answer?
Find an answer to your question 👍 “Write a program to initialize an ArrayList of Strings and insert ten words. Then, using Math. random, print two different Strings from the ...” in 📗 Computers & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers