每日一练87——Java彩色幽灵(8kyu)

题目

创建一个Ghost类

Ghost对象在没有任何参数的情况下被实例化。

实例化时,Ghost对象被赋予白色“或”黄色“或”紫色“或”红色“的随机颜色属性

Ghost ghost = new Ghost();
ghost.getColor(); //=> "white" or "yellow" or "purple" or "red"

测试用例:

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"));
    }
} 

解题

My

import java.util.Random;
public class Ghost {
    public static String getColor(){
        String[] arr = {"white","yellow","purple","red"};
        return arr[new Random().nextInt(4)];
    }
}

Other

import java.util.Random;

public class Ghost {
  private String[] m_colorCodes = new String[]{"white" , "yellow" , "purple" , "red"};
  private String m_color = "";
  
  public Ghost(){
    m_color = m_colorCodes[new Random().nextInt(m_colorCodes.length)];
  }
  
  public String getColor(){
    return m_color;
  }
}

后记

这题的测试用例我是真的没思路,还好解题后可以看到出题者写的测试用例。还有我的代码还是太嫩了,别人的代码就很像项目代码。

你可能感兴趣的:(每日一练87——Java彩色幽灵(8kyu))