1、简单控制台程序如下,如需界面需要自己加个。
package zhidao
import java.util.HashSet
import java.util.Random
import java.util.Scanner
import java.util.Set
/**
* @author bufei
* @datetime 2020年8月31日15:54:11
*/
public class YaoHao {
public static void main(String[] args) {
String xian = "= = = = = = = = ="
// 起点 终点 奖个数 指定的号码个数
int start = 0, end = 0, prizeNum = 0, defaNum = 0
System.out.println(xian)
System.out.println("欢迎使用xxx 抽奖系统!")
System.out.println(xian)
Scanner scanner = new Scanner(System.in)
System.out.println("请输入号码范围例如 1 10:")
start = scanner.nextInt()
end = scanner.nextInt()
System.out.println("请输入奖项个数:")
prizeNum = scanner.nextInt()
System.out.println("请输入指定中奖号码个数,不指定请输入0:")
defaNum = scanner.nextInt()
int[] defa = new int[defaNum]
if (defaNum != 0) {
System.out.println("请输入指定的中奖号码,空格隔开:")
for (int i = 0i <defaNumi++) {
defa[i] = scanner.nextInt()
}
}
System.out.println(xian)
System.out.println("本次抽奖中奖号码为:")
for (int num : randomDraw(start, end, prizeNum, defa)) {
System.out.print(num+" ")
}
}
/**
* @param start 抽奖范围起点
* @param end 抽奖号码范围终点
* @param prizeNum 中奖号码个数
* @param defa 指定中奖号码
* @return
*/
public static Set<Integer>randomDraw(int start, int end, int prizeNum, int[] defa) {
Set<Integer>set = new HashSet<>()
// 未指定中奖号码
if (defa.length == 0) {
//随机抽 prizeNum 个奖
while (set.size() <prizeNum) {
set.add(new Random().nextInt(end - start + 1) + start)
}
return set
} else {
//指定了中奖号码
//把指定的号码加入进去
for (int num : defa) {
set.add(num)
}
//如果没有全部指定 则继续抽剩余的奖项
while (set.size() <prizeNum - defa.length) {
set.add(new Random().nextInt(end - start + 1) + start)
}
return set
}
}
}
2、运行效果如图
指定了中奖号码
未指定中奖号码
未指定中奖号码
import java.awt.event.WindowAdapterimport java.awt.event.WindowEvent
import java.util.Random
import javax.swing.JFrame
import javax.swing.JTextField
public class RandomTest extends JFrame implements Runnable {
JTextField tf = new JTextField()
public RandomTest() {
this.add(tf)
this.setSize(300,200)
this.setVisible(true)
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
// System.exit(0)
dispose()
}
})
}
public void run() {
String[] list = { "aaa", "123", "张三", "李四" }
int time = 100//3秒钟出结果
Random rd = new Random()// 随机数生成类
int i = 0
while (time >0) {
try {
i = rd.nextInt(list.length)
tf.setText(list[i])
Thread.sleep(10)
time --
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace()
}
}
tf.setText("获奖者:" + list[i])
}
public static void main(String[] args) {
new Thread(new RandomTest()).start()
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)