输出A,B,C,D,E即可。
import java.util.ArrayList;
import java.util.List;
public class Ball {
/** 记录总共的可能性 */
private static int total = 0;
/** 记录该球可能性的其实范围 */
public int current = 0;
/** 记录该球的可能性 */
private int times = 0;
/** 记录该球的代表字母 */
private String name = null;
public Ball(int times, String name) {
this.current = total;
total += times;
this.times = times;
this.name = name;
}
/**
* 根据参数返回其对应的字符
*
* @param number
* :给定的参数
* @return:返回对应的字符
*/
public String play(int number) {
if (number < current + times && current <= number) {
return name;
} else {
return null;
}
}
/**
* 返回记录总共的可能性
*
* @return:记录总共的可能性
*/
private static double getTotal() {
return total;
}
public static void main(String[] args) {
// 实例化ball对象
Ball ball01 = new Ball(30, "A");
Ball ball02 = new Ball(50, "B");
Ball ball03 = new Ball(20, "C");
Ball ball04 = new Ball(40, "D");
Ball ball05 = new Ball(10, "E");
// 创建容器,并把求全放进容器
List<Ball> ballList = new ArrayList<Ball>();
ballList.add(ball01);
ballList.add(ball02);
ballList.add(ball03);
ballList.add(ball04);
ballList.add(ball05);
// 随机产生五个数字,并将其翻译成要表示的字符
for (int i = 0; i < 5; ++i) {
int number = (int) (Math.random() * Ball.getTotal());
PrintName(ballList, number);
}
}
/**
* 打印翻译以后的结果
*
* @param ballList
* :存放ball的容器
* @param number
* :给定的数字,由此数字产生对应的字母
*/
private static void PrintName(List<Ball> ballList, int number) {
for (Ball ball : ballList) {
String name = ball.play(number);
if (name != null) {
System.out.print(name + "\t");
}
}
}
}