How to Return Random Values in Java

The challenge

Ghost objects are instantiated without any arguments.

Ghost objects are given a random color attribute of white” or “yellow” or “purple” or “red” when instantiated

Ghost ghost = new Ghost(); ghost.getColor(); //=> "white" or "yellow" or "purple" or "red"
Code language: Java (java)

All this challenge is really asking us to do is to create a class method that can return random colour strings when called.

The solution in Java

We make use of the java.util.Random class to generate a couple of random values for us to use within a switch statement.

In each switch case, we can return one of our colours as desired.

import java.util.Random; public class Ghost { public String getColor() { Random rand = new Random(); switch(rand.nextInt(4)+1) { case 1: return "yellow"; case 2: return "white"; case 3: return "purple"; case 4: return "red"; } return "white"; } }
Code language: Java (java)

An even more succinct way to do this could be as follows:

public class Ghost { private final String[] colors = {"white", "yellow", "purple", "red"}; public Ghost() { } public String getColor() { return colors[(int)(Math.random() * colors.length)]; } }
Code language: Java (java)

Test cases to validate our approach

import org.junit.Test; import static org.junit.Assert.assertEquals; import java.util.ArrayList; public class GhostTests { private ArrayList ghostColors = new ArrayList(); public GhostTests() { for (int i = 1; i <= 100; i++) { ghostColors.add(new Ghost().getColor()); } } private Boolean ghostColor(ArrayList ghostColors, String color) { Boolean answer = false; for (int i = 0; i < ghostColors.size(); i++) { if (ghostColors.get(i) == color) { answer = true; break; } } return answer; }; @Test public void should_sometimes_make_white_ghosts() throws Exception { assertEquals("No white ghost found.", true, ghostColor(ghostColors, "white")); } @Test public void should_sometimes_make_yellow_ghosts() throws Exception { assertEquals("No yellow ghost found.", true, ghostColor(ghostColors, "yellow")); } @Test public void should_sometimes_make_purple_ghosts() throws Exception { assertEquals("No purple ghost found.", true, ghostColor(ghostColors, "purple")); } @Test public void should_sometimes_make_red_ghosts() throws Exception { assertEquals("No red ghost found.", true, ghostColor(ghostColors, "red")); } }
Code language: Java (java)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments