用java实现观众抽取问题

要求启动开始后能随机抽取存在文本文件中的若干个观众手机号码,显示时隐藏最后两位号码,并将获奖主题、获奖等级和获奖名单、手机号、获奖时间等保存在获奖的文本文件中,并可查询历史抽奖情况。
请问在已经实现部分功能的代码的基础上,如何实现记录抽奖时间并保存抽奖各项记录于文本文件的功能

import javax.swing.;
import java.awt.
;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Random;
import java.util.Vector;
public class Luckymode extends JFrame implements Runnable {
/**
* 文本”设置获奖人数:“
*/
JLabel numLabel, prizeLabel;
JComboBox numBox, prizeBox;
JButton startBtn, endBtn;
int number = 4;
boolean IS_RUNNING = false;
int i;
String FILE_PATH = "D:/information.txt";
JTextField[] phoneList = new JTextField[10];
Vector vector = new Vector<>();
Luckymode(String s) {
super(s);
initComponents();
}
public void initComponents() {
//界面初始化及监听事件
Container jtogether = getContentPane();
JPanel jup = new JPanel();
jup.setLayout(new FlowLayout());
prizeLabel = new JLabel("奖项:");
String[] prizes = {"一等奖", "二等奖", "三等奖"};
numLabel = new JLabel("人数:");
String[] nums = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
prizeBox = new JComboBox(prizes);
prizeBox.setSelectedIndex(2);
prizeBox.addActionListener(e -> {
IS_RUNNING = false;
startBtn.setEnabled(true);
endBtn.setEnabled(false);
for (i = 0; i < 10; i++) {
phoneList[i].setText("");
}
});
numBox = new JComboBox(nums);
numBox.setSelectedIndex(4);
numBox.addActionListener(e -> {
if (e.getSource() == numBox) {
IS_RUNNING = false;
startBtn.setEnabled(true);
endBtn.setEnabled(false);
number = numBox.getSelectedIndex();
for (i = 0; i < 10; i++) {
phoneList[i].setEditable(i <= number);
phoneList[i].setText("");
}
}
});
jup.add(prizeLabel);
jup.add(prizeBox);
jup.add(numLabel);
jup.add(numBox);

    JPanel jtemp = new JPanel();
    jtemp.setLayout(new BorderLayout());
    JPanel j1 = new JPanel();
    j1.add(new JLabel(" "));
    JPanel j2 = new JPanel();
    j2.add(new JLabel(" "));
    JPanel jcenter = new JPanel();
    jcenter.setLayout(new GridLayout(10, 1, 20, 0));
    for (i = 0; i < 10; i++) {
        phoneList[i] = new JTextField("");
        phoneList[i].setHorizontalAlignment(JTextField.CENTER);
        jcenter.add(phoneList[i]);
        phoneList[i].setEditable(i <= number);
    }
    jtemp.add("Center", jcenter);
    jtemp.add("West", j1);
    jtemp.add("East", j2);
    JPanel jdown = new JPanel();
    jdown.setLayout(new FlowLayout());
    startBtn = new JButton("开始");
    endBtn = new JButton("结束");
    startBtn.addActionListener(e -> {
        IS_RUNNING = true;
        startBtn.setEnabled(false);
        endBtn.setEnabled(true);
    });
    endBtn.addActionListener(e -> {
        IS_RUNNING = false;
        startBtn.setEnabled(true);
        endBtn.setEnabled(false);
    });
    endBtn.setEnabled(false);
    jdown.add(startBtn);
    jdown.add(endBtn);
    jtogether.setLayout(new BorderLayout());
    jtogether.add("North", jup);
    jtogether.add("Center", jtemp);
    jtogether.add("South", jdown);
    textinfile();
    setVisible(true);
}
public String texthand(String a) {
    //将从文件读入的数据处理
    return a.replaceAll("(\\d{3,3}).{4,4}(\\d{4,4})", "$1****$2");
}
public void textinfile() {
    //将文件中手机号码信息读入vector
    try (FileReader f = new FileReader(FILE_PATH); BufferedReader br = new BufferedReader(f)) {
        String strline = br.readLine();
        while (strline != null) {
            vector.add(texthand(strline));
            strline = br.readLine();
        }
    } catch (IOException e) {
        System.err.printf("文件不存在%s%n", e.getMessage());
    }
}
public void run() {      //线程运行
    Random random = new Random();
    while (true) {
        try {
            Thread.sleep((long) ((Math.random() * 100) + 50));
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.printf("is_running:%s%n", IS_RUNNING);
        if (IS_RUNNING) {
            int index;
            for (i = 0; i <= number; i++) {
                if (vector.size() > 0) {
                    // 在phoneList[i]中随机显示手机号码
                    index = random.nextInt(vector.size() - 1);
                    System.out.printf("update %d %s%n", index, vector.get(index));
                    phoneList[i].setText(vector.get(index));
                } else {
                    phoneList[i].setText("无");
                }
            }
        }
    }
}
public static void main(String[] args) {
    Luckymode luck = new Luckymode("幸运手机号码抽取");
    luck.setSize(300, 450);
    luck.setLocation(800, 300);
    luck.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    new Thread(luck).start();
}

尽量还是描述你哪个地方不明白或者实现不了。现在csdn官方不支持直接要代码的行为。对个人成长也无益


import javax.swing.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class Luckymode extends JFrame implements Runnable {
    /**
     * 文本”设置获奖人数:“
     */
    JLabel numLabel, prizeLabel;
    JComboBox numBox, prizeBox;
    JButton startBtn, endBtn,saveBtn;
    int number = 4;
    boolean IS_RUNNING = false;
    int i;
    String FILE_PATH = "D:/information.txt";
    String LOG_FILE_PATH = "D:/抽奖中奖记录名单.txt";
    JTextField[] phoneList = new JTextField[10];
    Vector<String> vector = new Vector<>();
    Vector<String> existsVector = new Vector<>();
    Map<String,String> map = new HashMap<>();
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    Luckymode(String s) {
        super(s);
        initComponents();
    }

    public void initComponents() {
        //界面初始化及监听事件
        Container jtogether = getContentPane();
        JPanel jup = new JPanel();
        jup.setLayout(new FlowLayout());
        prizeLabel = new JLabel("奖项:");
        String[] prizes = {"一等奖", "二等奖", "三等奖"};
        numLabel = new JLabel("人数:");
        String[] nums = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
        prizeBox = new JComboBox(prizes);
        prizeBox.setSelectedIndex(2);
        prizeBox.addActionListener(e -> {
            IS_RUNNING = false;
            startBtn.setEnabled(true);
            endBtn.setEnabled(false);
            saveBtn.setEnabled(false);
            for (i = 0; i < 10; i++) {
                phoneList[i].setText("");
            }
        });
        numBox = new JComboBox(nums);
        numBox.setSelectedIndex(4);
        numBox.addActionListener(e -> {
            if (e.getSource() == numBox) {
                IS_RUNNING = false;
                startBtn.setEnabled(true);
                endBtn.setEnabled(false);
                saveBtn.setEnabled(false);
                number = numBox.getSelectedIndex();
                for (i = 0; i < 10; i++) {
                    phoneList[i].setEditable(i <= number);
                    phoneList[i].setText("");
                }
            }
        });
        jup.add(prizeLabel);
        jup.add(prizeBox);
        jup.add(numLabel);
        jup.add(numBox);

        JPanel jtemp = new JPanel();
        jtemp.setLayout(new BorderLayout());
        JPanel j1 = new JPanel();
        j1.add(new JLabel(" "));
        JPanel j2 = new JPanel();
        j2.add(new JLabel(" "));
        JPanel jcenter = new JPanel();
        jcenter.setLayout(new GridLayout(10, 1, 20, 0));
        for (i = 0; i < 10; i++) {
            phoneList[i] = new JTextField("");
            phoneList[i].setHorizontalAlignment(JTextField.CENTER);
            jcenter.add(phoneList[i]);
            phoneList[i].setEditable(i <= number);
        }
        jtemp.add("Center", jcenter);
        jtemp.add("West", j1);
        jtemp.add("East", j2);
        JPanel jdown = new JPanel();
        jdown.setLayout(new FlowLayout());
        startBtn = new JButton("开始");
        endBtn = new JButton("结束");
        saveBtn = new JButton("保存中奖名单");

        startBtn.addActionListener(e -> {
            IS_RUNNING = true;
            startBtn.setEnabled(false);
            endBtn.setEnabled(true);
            saveBtn.setEnabled(false);
        });
        endBtn.addActionListener(e -> {
            IS_RUNNING = false;
            startBtn.setEnabled(true);
            endBtn.setEnabled(false);
            saveBtn.setEnabled(true);
        });

        saveBtn.addActionListener(e->{
            //保存中奖名单
            Vector<String> saveList = new Vector<>();
            for(int i=0;i<=number;i++){
                String text = phoneList[i].getText();
                if(text != null && !"".equals(text)){
                    String phone = map.get(text);
                    if(saveList.isEmpty()){
                        saveList.add(String.format("%s\t%s\t%s", dateTimeFormatter.format(LocalDateTime.now()),prizeBox.getSelectedItem().toString(),"中奖名单"));
                    }
                    saveList.add(phone==null?"无":phone);
                    removePhone(text);
                }
            }
            saveList.add("------------------------------");
            try {
                Path file = Paths.get(String.format(LOG_FILE_PATH,prizeBox.getSelectedItem().toString()));
                Files.write(file, saveList, StandardCharsets.UTF_8, StandardOpenOption.APPEND, StandardOpenOption.CREATE);
                JOptionPane.showMessageDialog(null, "保存成功", "提示", JOptionPane.INFORMATION_MESSAGE);
                saveBtn.setEnabled(false);
            }catch (Exception ex){
                ex.printStackTrace();
                JOptionPane.showMessageDialog(null, "保存失败", "提示", JOptionPane.ERROR_MESSAGE);
                System.err.printf("保存失败%s%n", ex.getMessage());
            }
        });

        endBtn.setEnabled(false);
        saveBtn.setEnabled(false);
        jdown.add(startBtn);
        jdown.add(endBtn);
        jdown.add(saveBtn);
        jtogether.setLayout(new BorderLayout());
        jtogether.add("North", jup);
        jtogether.add("Center", jtemp);
        jtogether.add("South", jdown);
        textinfile();
        setVisible(true);
    }

    public String texthand(String a) {
        //将从文件读入的数据处理
        return a.replaceAll("(\\d{3,3}).{4,4}(\\d{4,4})", "$1****$2");
    }

    public void textinfile() {
        //将文件中手机号码信息读入vector
        try (FileReader f = new FileReader(FILE_PATH); BufferedReader br = new BufferedReader(f)) {
            String strline = br.readLine();
            while (strline != null) {
                String hideText = texthand(strline);
                vector.add(hideText);
                map.put(hideText,strline);
                strline = br.readLine();
            }
        } catch (IOException e) {
            System.err.printf("文件不存在%s%n", e.getMessage());
        }
    }

    private void removePhone(String phone){
        vector.remove(phone);
    }


    public void run() {      //线程运行
        Random random = new Random();
        while (true) {
            try {
                Thread.sleep((long) ((Math.random() * 100) + 50));
            } catch (Exception e) {
                e.printStackTrace();
            }
            //System.out.printf("is_running:%s%n", IS_RUNNING);
            if (IS_RUNNING) {
                int index;
                int dataSize = vector.size()-1;
                existsVector.clear();
                if(dataSize>=0){
                    for(;;){
                        index = dataSize == 0?0:random.nextInt(dataSize);
                        String phone = vector.get(index);
                        if(!existsVector.contains(phone)){
                            existsVector.add(phone);
                        }
                        if(existsVector.size() == (number+1) || existsVector.size() == (dataSize+1)){
                            break;
                        }
                    }
                }
                for(int i=0;i<=number;i++){
                    phoneList[i].setText(i<=existsVector.size()-1?existsVector.get(i):"无");
                }

            }
        }
    }

    public static void main(String[] args) {
        Luckymode luck = new Luckymode("幸运手机号码抽取");
        luck.setSize(380, 450);
        luck.setLocation(800, 300);
        luck.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        new Thread(luck).start();
    }
}

在你原来的基础上增加:
1.增加保存中奖名单操作(如果想自动保存请将保存逻辑复制到结束按钮事件中)
2.增加每一次运行程序当前抽奖页面同一个号码去重
3.增加每一次运行程序同一个号码不能同时中不同级别等奖
4.获取名单自动保存在D:/抽奖中奖记录名单.txt

效果图;

img

img

img

img

如果你只是想要一个抽奖程序的话,这个就满足你的需求。
https://download.csdn.net/download/qq_19309473/68241550

1.将你的问题描述清楚
2.将你的需求说明清楚
3.自己动手尝试,遇到问题解决问题,遇到困难解决困难。

jQuery新年年会随机手机号码滚动抽奖代码 - 懒人之家

img

你这种作业问题,csdn的专家很乐意给你回答,你直接用有问必答问。

你还不如自己写,遇到问题再问

https://download.csdn.net/download/Waylon_Ma/20430396

这种抽奖的可以考虑用HTML + JS/JQuery来实现,几十行代码就可以实现全部功能啦;或者直接用Excel的随机函数来抽奖,这样还可以免编码,更适合办公族使用。

如果你对java完全没有了解,那么本回答没有意义。
首先你需要了解java-UI相关的API,先构建一个窗口给他设置简单的关闭事件。
然后在窗口中添加文本域和输入区以及按钮。
在输入区可以输入你想要输入的信息。
然后抽奖按钮设置监听事件,先对取得点击时输入区的数据,验证其格式。
然后你需要了解IO相关的API。
使用输入流进行数据读取,输出流进行数据保存。
在进行电话录入的时候,可以讲姓名和电话用一个特殊的分隔符分开。存入文件。
再读取时,读出一行,然后通过特殊的分隔符进行分割数据。
最后利用这个思路可以把数据先读取到一个集合当中。
然后你可以通过Math类的随机数参生办法进行随机抽取下标,并取出集合中的信息。
也可以通过Collections类带的打乱方法suffer来进行打乱后,取出前几位。
最后,在监听事件中,可以重新new一个窗口,在窗口中显示这些数据,然后把这些数据通过
输出流保存。
如果你希望具备模态,那么可以基础弹窗类进行重写。

可以百度一个模板去做

用字节流将手机存入文本文件中,抽奖的时候读取出来放进数组,通过random随机生成一个下标,将中奖手机存入另一个文本文档,或者存入数据库

现在问答只要是讨论问题,不是做外包项目的,你可以把你遇到的困难列出来。

回答:这边采用C#简单做了一个,由于C#做起来更快,相对来说描述起来也比较简单,如果觉得没啥问题,改成java编写,也不是太难(主要个人对C#比较熟悉,Java的用户界面做的很少,倒不失为一个锻炼的好机会);大体的功能基本符合你的描述(你的描述相对来说还是比较清晰的,功能模块也比较简单)
运行截图:

img


没有给名称则全部查找

img


给了名称就筛选

img

大题上的功能就这些,主要代码如下:

主窗体代码

using System;
using System.Windows.Forms;

namespace lottery
{
    public partial class Form1 : Form
    {
        Lottery_Action action = new Lottery_Action();

        public Form1()
        {
            InitializeComponent();
        }

        private void button_lottery_Click(object sender, EventArgs e)
        {
            action.Start_Lottery();
            label_result.Text = action.result;
        }

        private void button_add_msg_Click(object sender, EventArgs e)
        {
            string audience_name = textBox_audience_name.Text;
            string audience_tel = textBox_audience_tel.Text;
            action.Add_person_msg(audience_name, audience_tel);
        }

        private void button_set_Click(object sender, EventArgs e)
        {
            action.theme = textBox_theme.Text;
            action.level = textBox_level.Text;
            action.number = textBox_number.Text;
            MessageBox.Show("设定成功");
        }

        private void button_history_inquiry_Click(object sender, EventArgs e)
        {
            History form = new History();
            form.ShowDialog();
        }
    }
}

执行动作类

using System;
using System.IO;
using System.Windows.Forms;

namespace lottery
{
    public class Lottery_Action
    {
        public string theme = "", level = "", number = "", result = "";

        private int Get_file_linenumber()
        {
            int counter = 0;
            string path = "audience.txt";
            if (File.Exists(path))
            {
                foreach (string line in System.IO.File.ReadLines("audience.txt"))
                {
                    counter++;
                }
                return counter;
            }
            else
                return 0;
        }

        private int Judge_lottery_number()
        {
            int lottery_number;

            if (number != "" && int.TryParse(number, out _))
                lottery_number = int.Parse(number);
            else
                lottery_number = 0;
            return lottery_number;
        }

        /*不存在则返回真*/
        private bool Is_contains(int[] _Array, int _num)
        {
            if (Array.IndexOf(_Array, _num) == -1)
                return true;
            else
                return false;
        }

        private void Get_random_number(int[] Produce_array, int produce_number)
        {
            Random random = new Random();
            int produce_range = Get_file_linenumber(), count = 1;

            while (count < produce_number)
            {
                int num = random.Next(produce_range);
                if (Is_contains(Produce_array, num))
                {
                    Produce_array[count - 1] = num;
                    count++;
                }
            }           
        }

        public void Start_Lottery()
        {
            string path = "audience.txt";
            int lottery_number = Judge_lottery_number(), current_line = 0;
            int[] Produce_array = new int[lottery_number];

            if (File.Exists(path))
            {
                if (Get_file_linenumber() < lottery_number)
                {
                    MessageBox.Show("录入人数不够");
                    return;
                }

                string[] lines = File.ReadAllLines("audience.txt");

                Get_random_number(Produce_array, lottery_number);
                Array.Sort(Produce_array);

                foreach (string line in lines)
                {
                    if (Array.IndexOf(Produce_array, current_line) != -1)
                    {
                        string[] Array = line.Split('\t');
                        Save_history(Array[0], Array[1]);
                        if (Array[1].Length >= 2)
                        {
                            Array[1] = Array[1].Remove(Array[1].Length - 2);
                            Array[1] = Array[1].Insert(Array[1].Length, "**");
                        }
                        result += Array[0] + "    " + Array[1] + "\n";
                    }
                    current_line++;
                }
                MessageBox.Show("抽奖成功");
            }
            else
                MessageBox.Show("文件不存在");
        }

        public void Save_history(string audience_name, string audience_tel)
        {
            string save_input = theme + "\t" + level + "\t" + audience_name + "\t" + audience_tel + "\t" + DateTime.Now.ToString();

            string path = "lottery_history.txt";
            StreamWriter streamWriter = new StreamWriter(path, true);
            streamWriter.WriteLine(save_input);
            streamWriter.Flush();
            streamWriter.Close();
        }

        public void Add_person_msg(string audience_name, string audience_tel)
        {           
            string input = audience_name + "\t" + audience_tel;

            if (audience_name != "" && audience_tel != "")
            {
                string path = "audience.txt";
                StreamWriter streamWriter = new StreamWriter(path, true);
                streamWriter.WriteLine(input);
                streamWriter.Flush();
                streamWriter.Close();
                MessageBox.Show("录入成功");
            }
            else
                MessageBox.Show("姓名、手机号不能为空");
        }
    }
}

剩下的就不全给了,下载链接为:(这边是用VS2019编写,要运行也需要VS2010以上版本)
链接:https://pan.baidu.com/s/1UzwO4gEXP2y7z6ZHGDXoJw
提取码:0925

最后附注:不要采纳哈,毕竟不符合要求,等我看看Java版本啥时候写出来;另外这次编写程序收获也不小,共同进步哈

一、java-UI相关的API知识

  1. 先构建一个窗口给他设置简单的关闭事件。
  2. 在窗口中添加文本域和输入区以及按钮。
  3. 在输入区可以输入你想要输入的信息。
  4. 然后抽奖按钮设置监听事件,先对取得点击时输入区的数据,验证其格式。
    二、IO相关的API知识
  5. 使用输入流进行数据读取,输出流进行数据保存。
  6. 在进行电话录入的时候,可以讲姓名和电话用一个特殊的分隔符分开。存入文件。
  7. 在读取时,读出一行,然后通过特殊的分隔符进行分割数据。
  8. 利用这个思路可以把数据先读取到一个集合当中。
  9. 通过Math类的随机数参生办法进行随机抽取下标,并取出集合中的信息。
    或者通过Collections类带的打乱方法suffer来进行打乱后,取出前几位。
  10. 在监听事件中,可以重新new一个窗口,在窗口中显示这些数据,然后把这些数据通过输出流保存。
  11. 如果你希望具备模态,可以基础弹窗类进行重写。

尽量还是描述你哪个地方不明白或者实现不了。现在csdn官方不支持直接要代码的行为。对个人成长帮助不大,还需要讨论有自己的钻研

尽量还是描述你哪个地方不明白或者实现不了。现在csdn官方不支持直接要代码的行为。对个人成长帮助不大,还需要讨论有自己的钻研


import java.util.Random;
public class UseRandom {
public static void main(String args[]){
int i;
Random r=new Random(); 
for(i=0;i<10;i++)
{
int m= r.nextInt(20); //这里面数字是随机数的上限
double mm=(double)m;
System.out.println(Math.sqrt(mm));
}
}
}

记录进行保存需要编写相关的io操作,理论上也不太困难

这个问题网上应该一大堆,花点时间一下就处理了

这个网上有很多demo

用 Java 开发这种桌面软件是很费劲的,一般桌面软件都是用C#、C++开发,不要在Java上浪费时间了。

java 抽奖,网上一大堆