用JAVA编写 GUI 界面,模拟抢红包游戏,在界面输入红包大小和抢红包人姓名(用逗号隔开),输出系统当前时间以及每个人抢的红包大小,要求每个人抢的红包最少不能少于0.01元
时间: 2024-04-04 22:30:44 浏览: 61
好的,以下是使用 Java 编写的 GUI 界面,模拟抢红包游戏,实现在界面输入红包大小和抢红包人姓名(用逗号隔开),输出系统当前时间以及每个人抢的红包大小,要求每个人抢的红包最少不能少于0.01元:
```java
import java.awt.*;
import java.awt.event.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import javax.swing.*;
public class RedPacketGame extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JLabel redPacketLabel, nameLabel, resultLabel;
private JTextField redPacketField, nameField;
private JButton submitButton;
public RedPacketGame() {
super("抢红包游戏");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(3, 2));
setSize(400, 150);
redPacketLabel = new JLabel("红包大小:");
add(redPacketLabel);
redPacketField = new JTextField();
add(redPacketField);
nameLabel = new JLabel("抢红包人姓名:");
add(nameLabel);
nameField = new JTextField();
add(nameField);
submitButton = new JButton("抢红包");
add(submitButton);
submitButton.addActionListener(this);
resultLabel = new JLabel();
add(resultLabel);
}
@Override
public void actionPerformed(ActionEvent e) {
double redPacket = Double.parseDouble(redPacketField.getText().trim());
String[] names = nameField.getText().trim().split(",");
int numPeople = names.length;
double minAmount = 0.01;
if (redPacket < numPeople * minAmount) {
resultLabel.setText("红包太少啦,每个人至少能分到0.01元哦!");
return;
}
double[] amounts = new double[numPeople];
double remainAmount = redPacket;
Random random = new Random();
for (int i = 0; i < numPeople - 1; i++) {
double amount = Math.round(remainAmount / (numPeople - i) * 2 * random.nextDouble() * 100) / 100.0;
amounts[i] = amount;
remainAmount -= amount;
}
amounts[numPeople - 1] = Math.round(remainAmount * 100) / 100.0;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String timeStr = dateFormat.format(new Date());
StringBuilder resultStr = new StringBuilder("系统当前时间:" + timeStr + "\n");
for (int i = 0; i < numPeople; i++) {
String name = names[i];
double amount = amounts[i];
resultStr.append(name).append(" 抢到 ").append(amount).append(" 元\n");
}
resultLabel.setText(resultStr.toString());
}
public static void main(String[] args) {
RedPacketGame game = new RedPacketGame();
game.setVisible(true);
}
}
```
运行代码后,会出现一个简单的 GUI 界面,里面有两个输入框和一个按钮。在红包大小的输入框中输入红包大小,在抢红包人姓名的输入框中输入抢红包人姓名(多个人姓名之间用逗号隔开),然后点击“抢红包”按钮,程序会自动计算每个人抢到的红包金额,并在界面上显示系统当前时间和每个人抢到的红包金额。如果红包太少,无法保证每个人抢到的金额不少于0.01元,则会在界面上提示红包太少的消息。
阅读全文