5. Method generateSecretCode() Instantiate and instance of Java API class Random
ID: 3871165 • Letter: 5
Question
5.Method generateSecretCode()
Instantiate and instance of Java API class Random
Loop until four of the eight colors have been randomly selected to be the secret code with no duplicates (hint: member variable secretCode is of type Set which automatically does not allow for duplicates)
i.Use the method .nextInt() in class Random to select an index into the Constants.codeColors ArrayList, pass the ArrayList as an argument to the method call
ii.Create an instance of Java API class Color and set it equal to the color stored at the index of the Constants.codeColors ArrayList by calling the get() method in class ArrayList passing the int from step i. above as an argument
iii.Add the selected color to the Set member variable by calling method .add in class Set passing the Color object from step ii. above as and argument
Use an enhanced for loop to output the generated secret code
5.Method generateSecretCode()
Instantiate and instance of Java API class Random
Loop until four of the eight colors have been randomly selected to be the secret code with no duplicates (hint: member variable secretCode is of type Set which automatically does not allow for duplicates)
i.Use the method .nextInt() in class Random to select an index into the Constants.codeColors ArrayList, pass the ArrayList as an argument to the method call
ii.Create an instance of Java API class Color and set it equal to the color stored at the index of the Constants.codeColors ArrayList by calling the get() method in class ArrayList passing the int from step i. above as an argument
iii.Add the selected color to the Set member variable by calling method .add in class Set passing the Color object from step ii. above as and argument
Use an enhanced for loop to output the generated secret code
Explanation / Answer
import java.util.*;
import java.lang.*;
import java.io.*;
import java.awt.Color;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{ static Set<Color> secretCode;
public static void main (String[] args) throws java.lang.Exception
{ int num;
while (secretCode.size()<4)
{ Random r = new Random();
num=r.nextInt(8);
Color newColor= Constants.codeColors.get(num);
secretCode.add(newColor);
}
for (Iterator<Color> it = secretCode.iterator(); it.hasNext(); ) {
System.out.print(it);
}
}
}
class Constants{
public static ArrayList<Color> codeColors = new ArrayList<>(Arrays.asList(Color.BLACK, Color.GREEN, Color.RED, Color.YELLOW,
Color.MAGENTA, Color.ORANGE, Color.PINK, Color.WHITE));
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.