要求:用面向对象的思想编程实现双色球,6个红球加1个蓝球,红球从1到33,出现过的红球将不能再次出现,蓝球从1到16中随机选出一个。
1 新建一个Ball类,用来表示双色球的摇奖用的数字球
package cn.libill;
/**
* 球(双色球摇奖用的数字球)
* @author libill
*
*/
public class Ball {
private int number; //球的号码
private boolean used; //球是否被使用过
/**
* number属性的访问器
* @return number 球的号码
*/
public int getNumber() {
return number;
}
/**
* used属性的访问器
* @return used true表示球被使用过,false表示球没有被使用过
*/
public boolean isUsed() {
return used;
}
/**
* used属性的修改器
* @param used true表示球被使用过,false表示球没有被使用过
*/
public void setUsed(boolean used) {
this.used = used;
}
/**
* 获取字符串形式的球的号码
* @return 字符串形式的号码
*/
public String getNumStr() {
return number < 10 ? "0" + number : "" + number;
}
/**
* 构造器
* @param number 球的号码
*/
public Ball(int number) {
this.number = number;
this.used = false;
}
}
2 创建一个LotteryMachine类,用来模拟双色球摇号的机器
package cn.libill;
import java.util.Arrays;
import java.util.Comparator;
/**
* 双色球摇号机
* @author libill
*
*/
public class LotteryMachine {
private Ball[] redBalls = new Ball[33]; //装红色球
private Ball[] blueBalls = new Ball[16]; //装蓝色球
/**
* 装入红色球和蓝色球
*/
public void load() {
for (int i = 0; i < redBalls.length; ++i) {
redBalls[i] = new Ball(i + 1);
}
for (int j = 0; j < blueBalls.length; ++j) {
blueBalls[j] = new Ball(j + 1);
}
}
/**
* 揺蓝色球
* @return
*/
public Ball getBlueBall() {
return blueBalls[(int) (Math.random() * blueBalls.length)];
}
public Ball[] getRedBalls() {
Ball[] balls = new Ball[6];
for (int i = 0; i < balls.length; ++i) {
Ball tempBall = null;
do {
int randomIndex = (int) (Math.random() * redBalls.length);
tempBall = redBalls[randomIndex];
} while (tempBall.isUsed());
balls[i] = tempBall;
tempBall.setUsed(true); //表示这颗球已经用过了
}
Arrays.sort(balls, new Comparator<Ball>() {
@Override
public int compare(Ball arg0, Ball arg1) {
return arg0.getNumber() - arg1.getNumber();
}
});
return balls;
}
/**
* 生成随机号码
* @return 随机号码的字符串
*/
public String generateRandomNumber() {
load();
Ball[] rBalls = getRedBalls();
Ball bBall = getBlueBall();
String str = "";
for (Ball x : rBalls) {
str += x.getNumStr() + " ";
}
str += "| ";
str += bBall.getNumStr();
return str;
}
}
3 测试程序
package cn.libill;
import java.util.Scanner;
public class TestLotteryMachine {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("机选几注:");
int n = sc.nextInt();
LotteryMachine lm = new LotteryMachine();
for (int i = 0; i < n; i++) {
System.out.println(lm.generateRandomNumber());
}
sc.close();
}
}
总结:
- 编写一个Ball类,它有球号和是否被使用两个属性,使得6上红球互不相同的实现更加容易
- 在LotteryMachine类中,用数组的方式将摇出的号码进行存储,方便对各球的操作和排序