欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

生成随机数,可用于彩票 Java 

程序员文章站 2024-02-26 11:14:28
...
package test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Ball {

	private List<Integer> redBalls;
	private Integer blueBall;

	public Ball() {
		calculateRedBalls();
		calculateBlueBall();
	}

	private void calculateRedBalls() {
		List<Integer> balls = new ArrayList<Integer>();
		for (int i = 1; i <= 33; i++) {
			balls.add(i);
		}
		Collections.shuffle(balls);
		redBalls = new ArrayList<Integer>(balls.subList(0, 6));
		Collections.sort(redBalls);
	}

	private void calculateBlueBall() {
		blueBall = (int) (Math.random() * 16 + 1);
	}

	@Override
	public String toString() {
		return "红色球是: " + redBalls + " and蓝色球是: " + blueBall;
	}

	public static void main(String[] args) {
		Ball ball = new Ball();
		System.out.println(ball);
	}

}


以上是引用别人的,还可以有另一种方法

package test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Vector;

public class Test {
	static Random r = new Random();
	public static int getRandomIntWithinRange(int cap) {
		return r.nextInt(cap)+1;
	}
	/**
	 * @param cap 最大到多少,如35,最大到35
	 * @param count,总共产生几个数,如5,产生5个数
	 * */
	public static Vector getRandomIntArrayWithinRange(int count, int cap) {
		Vector v = new Vector();
		Vector ret = new Vector();
		for(int i=1;i<=cap;i++) {
			v.add(new Integer(i));
		}
		//确保不重复
		for(int i=1;i<=count;i++) {
			int index = getRandomIntWithinRange(cap+1-i);
			ret.add(v.remove(index-1));
		}
		Collections.sort(ret);
		return ret;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Vector v=getRandomIntArrayWithinRange(5,35);
		String s=""+v;
		
		s=s.replace("[", "");
		s=s.replace("]", "");
	
		System.out.println(s);


	}

}
相关标签: Java