最近老大给我们出了一道题,要求纯文本编程......
要求:实现双色球机选N注
下面是大牛版的代码:反正我是比较推崇,仅供参考。
import java.awt.Color;
import java.util.Random;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
class Ball implements Comparable<Ball> {
private int number;
private Color color;
public Ball(int number, Color color) {
this.number = number;
this.color = color;
}
public int getNumber() {
return number;
}
public Color getColor() {
return color;
}
@Override
public int compareTo(Ball other) {
return this.number - other.number;
}
}
class SelectNumberMachine {
private static Random r = new Random();
private List<Ball> redBalls = new ArrayList<>();
private List<Ball> blueBalls = new ArrayList<>();
public void reset() {
redBalls.clear();
for (int i = 1; i <= 33; ++i) {
redBalls.add(new Ball(i, Color.RED));
}
blueBalls.clear();
for (int i = 1; i <= 16; ++i) {
blueBalls.add(new Ball(i, Color.BLUE));
}
}
public String generate() {
Ball[] currentRedBalls = selectRedBalls();
Arrays.sort(currentRedBalls);
Ball currentBlueBall = selectBlueBall();
StringBuilder sb = new StringBuilder();
for (Ball tempBall : currentRedBalls) {
sb.append(String.format("%02d ", tempBall.getNumber()));
}
sb.append("| ");
sb.append(String.format("%02d", currentBlueBall.getNumber()));
return sb.toString();
}
private Ball[] selectRedBalls() {
Ball[] currentRedBalls = new Ball[6];
for (int i = 0; i < currentRedBalls.length; ++i) {
int randomIndex = r.nextInt(redBalls.size());
currentRedBalls[i] = redBalls.remove(randomIndex);
}
return currentRedBalls;
}
private Ball selectBlueBall() {
int randomIndex = r.nextInt(blueBalls.size());
return blueBalls.remove(randomIndex);
}
}
class Test {
public static void main(String[] args) {
SelectNumberMachine machine = new SelectNumberMachine();
for (int i = 0; i < 10; ++i) {
machine.reset();
System.out.println(machine.generate());
}
}
}