package demo;
import java.io.FileOutputStream;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
public class Ball {
/**
* 简单的彩票中奖程序
*/
private int count = 0;// 计数器
// 一调用此方法就开始摇球
public void start() {
Scanner sc = new Scanner(System.in);
System.out.println("希望你中奖...");
// 1.避免出现重复的号码,用了HashSet来保存信息,避免了重复问题
Set set = new HashSet();
while (set.size() < 7) {
Random r = new Random();
int num = r.nextInt(36) + 1;
set.add(num);
}
// 2.产生的号码经由迭代,通过FileOutputStream存入a.txt文件中
Iterator it = set.iterator();
FileOutputStream fos = null;
try {
fos = new FileOutputStream("a.txt", true);// true追加信息
fos.write("本期中奖号码: ".getBytes());
while (it.hasNext()) {// 迭代器判断是否存在集合元素
String strnum = ((Integer) it.next()).toString();
System.out.println("第 " + (count + 1) + "个摇出来的的号码是: " + strnum);
sc.next();
fos.write(strnum.getBytes());
fos.write("/t".getBytes());
count++;
}
fos.write("/r/n".getBytes());
} catch (Exception e) {// 捕获异常
e.printStackTrace();
} finally {
if (fos != null) {// 若输出流不为空,则关闭输出流。
try {
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
Ball b = new Ball();// main中调用方法
b.start();
}
}