1.首先找到双色球的属性:双色球上的数字,双色球的颜色;为其进行定义
public final class Ball { private final int number; private final BallColor color; public Ball(int num, BallColor color) { this.number = num; this.color = color; } public int getNumber() { return number; } public BallColor getColor() { return color; } @Override public String toString() { return "(" + number + ", " + color + ")"; } }
讯享网
2.其中双色球的颜色使用枚举类型
讯享网public enum BallColor { RED("红球"), BLUE("兰球"); private String name; private BallColor(String name) { this.name=name; } @Override public String toString() { return this.name; } }
3.定义好双色球之后需要一个存放六个红球以及一个蓝球的数组,在数组类内包含增删改查的方法,以及对颜色比较的方法
public class ArrayList { private Ball[] arr; private int size = 0; public ArrayList() { this(10); } public ArrayList(int length) { arr = new Ball[length]; } public void add(Ball data) { arr[size++]=data; if(size>=arr.length) resize(); } / * @param index 需要删除的数据下标 */ public Ball delete(int index) { if(index>=size || size<0) throw new ArrayIndexOutOfBoundsException(); Ball res=arr[index]; System.arraycopy(arr, index+1, arr,index, arr.length-index-1); arr[size-1]=null; size--; return res; } public void update(int index,Ball data) { if(index>=size || size<0) throw new ArrayIndexOutOfBoundsException(); arr[index]=data; } public Ball[] getData() { Ball[] res=new Ball[size]; System.arraycopy(arr, 0, res, 0, size); return res; } public String toString() { return Arrays.toString(arr); } private void resize() { Ball[] res=new Ball[arr.length*3/2]; System.arraycopy(arr, 0, res, 0, arr.length); this.arr=res; } public int size() { return this.size; } public Ball[] sort() { Ball[] res=getData(); // Comparator<Ball> com=new Comparator<Ball>() { // @Override // public int compare(Ball o1, Ball o2) { // int res=o1.getColor().compareTo(o2.getColor()); // if(res==0) { // res=o1.getNumber()-o2.getNumber(); // } // res*=-1; // return res; // } // }; // Arrays.sort(res, com); Arrays.sort(res,(o1,o2)->{ int res1=o1.getColor().compareTo(o2.getColor()); if(res1==0) { res1=o1.getNumber()-o2.getNumber(); } res1*=-1; return res1; }); return res; } }
4.在测试类中添加主方法实现双色球
讯享网//红色球号码从1--33中选择;蓝色球号码从1--16中选择 //每注投注号码由6个红色球号码和1个蓝色球号码组成 public class Test1 { public static void main(String[] args) { ArrayList list1 = new ArrayList(); for (int i = 1; i <= 33; i++) list1.add(new Ball(i, BallColor.RED)); ArrayList list3 = new ArrayList(7); Random r = new Random(); for (int i = 0; i < 6; i++) { int pos=r.nextInt(list1.size()); Ball data=list1.delete(pos); list3.add(data); } list3.add(new Ball(r.nextInt(16)+1, BallColor.BLUE)); list3.sort(); Ball[] res=list3.getData(); System.out.println(Arrays.toString(res)); } }

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/106378.html