本文目录导读:

我来为您提供几个Java感恩节相关的案例,从简单到复杂,帮助您理解Java编程的不同方面。
案例1:简单的感恩节祝福程序
import java.time.LocalDate;
import java.time.Month;
public class ThanksgivingGreeting {
public static void main(String[] args) {
// 获取当前日期
LocalDate today = LocalDate.now();
// 检查是否是感恩节(美国:11月第4个星期四)
if (isThanksgiving(today)) {
System.out.println("🎉 感恩节快乐!🎉");
} else {
System.out.println("今天不是感恩节,但依然要心存感恩!");
}
// 打印感恩祝福
printThankfulMessage();
}
// 判断是否是感恩节
public static boolean isThanksgiving(LocalDate date) {
if (date.getMonth() != Month.NOVEMBER) {
return false;
}
// 获取当月第1天
LocalDate firstDay = date.withDayOfMonth(1);
// 获取第1天的星期几(1=周一,7=周日)
int dayOfWeek = firstDay.getDayOfWeek().getValue();
// 计算第4个星期四的日期
// 如果第1天是周4(dayOfWeek=4),则第4个周四是22日
// 否则需要计算
int daysToFirstThursday = (4 - dayOfWeek + 7) % 7;
int thanksgivingDay = 1 + daysToFirstThursday + 21; // 第4个周四
return date.getDayOfMonth() == thanksgivingDay;
}
// 打印感恩消息
public static void printThankfulMessage() {
String[] messages = {
"感谢家人给予的温暖与支持",
"感谢朋友在生活中带来的欢笑",
"感谢每一次挑战带来的成长机会",
"感谢生活中的美好事物",
"感谢每一个关心我的人"
};
System.out.println("\n🙏 感恩时刻 🙏");
for (String message : messages) {
System.out.println("• " + message);
}
}
}
案例2:感恩节礼物清单管理器
import java.util.ArrayList;
import java.util.Scanner;
public class GiftListManager {
private ArrayList<String> giftIdeas;
private ArrayList<String> recipients;
public GiftListManager() {
giftIdeas = new ArrayList<>();
recipients = new ArrayList<>();
}
// 添加礼物想法
public void addGiftIdea(String idea) {
giftIdeas.add(idea);
System.out.println("✅ 已添加礼物想法: " + idea);
}
// 添加收礼人
public void addRecipient(String name) {
recipients.add(name);
System.out.println("✅ 已添加收礼人: " + name);
}
// 显示所有内容
public void displayList() {
System.out.println("\n=== 🎁 感恩节礼物清单 🎁 ===");
System.out.println("\n📋 收礼人名单:");
if (recipients.isEmpty()) {
System.out.println(" 暂无收礼人");
} else {
for (int i = 0; i < recipients.size(); i++) {
System.out.println((i + 1) + ". " + recipients.get(i));
}
}
System.out.println("\n💡 礼物想法:");
if (giftIdeas.isEmpty()) {
System.out.println(" 暂无礼物想法");
} else {
for (int i = 0; i < giftIdeas.size(); i++) {
System.out.println((i + 1) + ". " + giftIdeas.get(i));
}
}
System.out.println("\n🔢 总计: " + recipients.size() + "位收礼人, " +
giftIdeas.size() + "个礼物想法");
}
// 删除项目
public void removeItem(int index, boolean isGift) {
if (isGift) {
if (index >= 0 && index < giftIdeas.size()) {
String removed = giftIdeas.remove(index);
System.out.println("🗑️ 已删除礼物想法: " + removed);
}
} else {
if (index >= 0 && index < recipients.size()) {
String removed = recipients.remove(index);
System.out.println("🗑️ 已删除收礼人: " + removed);
}
}
}
// 主菜单交互
public static void main(String[] args) {
GiftListManager manager = new GiftListManager();
Scanner scanner = new Scanner(System.in);
System.out.println("🎉 欢迎使用感恩节礼物清单管理器!🎉");
while (true) {
System.out.println("\n请选择操作:");
System.out.println("1. 添加收礼人");
System.out.println("2. 添加礼物想法");
System.out.println("3. 显示所有内容");
System.out.println("4. 删除收礼人");
System.out.println("5. 删除礼物想法");
System.out.println("6. 退出");
System.out.print("请输入选择 (1-6): ");
int choice = scanner.nextInt();
scanner.nextLine(); // 消耗换行符
switch (choice) {
case 1:
System.out.print("请输入收礼人姓名: ");
String name = scanner.nextLine();
manager.addRecipient(name);
break;
case 2:
System.out.print("请输入礼物想法: ");
String idea = scanner.nextLine();
manager.addGiftIdea(idea);
break;
case 3:
manager.displayList();
break;
case 4:
manager.displayList();
System.out.print("请输入要删除的收礼人序号: ");
int recIndex = scanner.nextInt() - 1;
manager.removeItem(recIndex, false);
break;
case 5:
manager.displayList();
System.out.print("请输入要删除的礼物想法序号: ");
int giftIndex = scanner.nextInt() - 1;
manager.removeItem(giftIndex, true);
break;
case 6:
System.out.println("感谢使用,祝您感恩节快乐!🎉");
scanner.close();
return;
default:
System.out.println("无效选择,请重新输入。");
}
}
}
}
案例3:感恩节美食食谱管理器
import java.util.HashMap;
import java.util.Map;
public class ThanksgivingRecipeManager {
private Map<String, Recipe> recipes;
// 内部类:食谱
class Recipe {
String name;
String[] ingredients;
String instructions;
int prepTime; // 准备时间(分钟)
int cookTime; // 烹饪时间(分钟)
Recipe(String name, String[] ingredients, String instructions,
int prepTime, int cookTime) {
this.name = name;
this.ingredients = ingredients;
this.instructions = instructions;
this.prepTime = prepTime;
this.cookTime = cookTime;
}
void displayRecipe() {
System.out.println("\n🍽️ " + name);
System.out.println("⏱️ 准备时间: " + prepTime + "分钟");
System.out.println("⏱️ 烹饪时间: " + cookTime + "分钟");
System.out.println("⏱️ 总时间: " + (prepTime + cookTime) + "分钟");
System.out.println("\n📝 食材:");
for (String ingredient : ingredients) {
System.out.println(" • " + ingredient);
}
System.out.println("\n👨🍳 制作步骤:");
System.out.println(instructions);
}
}
// 构造函数
public ThanksgivingRecipeManager() {
recipes = new HashMap<>();
initializeClassicRecipes();
}
// 初始化经典感恩节食谱
private void initializeClassicRecipes() {
// 火鸡食谱
String[] turkeyIngredients = {
"1只火鸡(约12-14磅)",
"1/2杯融化的黄油",
"2茶匙盐",
"1茶匙黑胡椒",
"2茶匙蒜粉",
"1茶匙迷迭香",
"1茶匙百里香",
"1个柠檬(切片)",
"1个洋葱(切块)"
};
String turkeyInstructions = """
1. 预热烤箱至325°F (163°C)
2. 清洗火鸡并擦干
3. 将黄油与香料混合,涂抹在火鸡表面
4. 在火鸡腔内放入柠檬和洋葱
5. 烤制约3-3.5小时,直到内部温度达到165°F
6. 休息15-20分钟后切块享用
""";
addRecipe("烤火鸡", new Recipe("传统烤火鸡", turkeyIngredients,
turkeyInstructions, 30, 210));
// 南瓜派食谱
String[] pieIngredients = {
"1个预制的派皮",
"2杯南瓜泥",
"1杯糖",
"1茶匙肉桂粉",
"1/2茶匙姜粉",
"1/4茶匙丁香粉",
"3个鸡蛋",
"1杯淡奶油",
"1茶匙香草精"
};
String pieInstructions = """
1. 预热烤箱至350°F (175°C)
2. 将派皮放入9寸派盘
3. 混合南瓜泥、糖和香料
4. 加入鸡蛋、淡奶油和香草精,搅拌至顺滑
5. 倒入派皮
6. 烤制45-50分钟,直到中心凝固
7. 冷却后切片享用
""";
addRecipe("南瓜派", new Recipe("经典南瓜派", pieIngredients,
pieInstructions, 20, 50));
}
// 添加食谱
public void addRecipe(String key, Recipe recipe) {
recipes.put(key, recipe);
System.out.println("✅ 已添加食谱: " + recipe.name);
}
// 查找食谱
public Recipe searchRecipe(String name) {
return recipes.get(name);
}
// 显示所有食谱
public void displayAllRecipes() {
System.out.println("\n📚 感恩节食谱大全");
System.out.println("=" .repeat(40));
for (Map.Entry<String, Recipe> entry : recipes.entrySet()) {
entry.getValue().displayRecipe();
System.out.println("-".repeat(40));
}
}
// 计算总烹饪时间
public int calculateTotalCookTime() {
int totalTime = 0;
for (Recipe recipe : recipes.values()) {
totalTime += recipe.prepTime + recipe.cookTime;
}
return totalTime;
}
public static void main(String[] args) {
ThanksgivingRecipeManager manager = new ThanksgivingRecipeManager();
System.out.println("🎄 感恩节美食准备助手 🎄");
System.out.println("=" .repeat(40));
// 显示所有食谱
manager.displayAllRecipes();
// 显示准备信息
System.out.println("\n⏰ 准备提醒:");
System.out.println("建议提前 " + manager.calculateTotalCookTime() +
" 分钟开始准备所有食谱");
// 查找特定食谱
System.out.println("\n🔍 查找食谱示例:");
Recipe turkey = manager.searchRecipe("烤火鸡");
if (turkey != null) {
System.out.println("找到食谱: " + turkey.name);
System.out.println("需要食材: " + turkey.ingredients.length + "种");
}
System.out.println("\n🎉 祝您感恩节大餐成功!🎉");
}
}
案例4:图形化感恩节卡片生成器
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ThanksgivingCardGenerator extends JFrame {
private JTextArea messageArea;
private JComboBox<String> backgroundStyle;
private JComboBox<String> fontStyle;
private JPanel previewPanel;
public ThanksgivingCardGenerator() {
setTitle("🦃 感恩节卡片生成器");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600, 500);
setLocationRelativeTo(null);
// 创建主面板
JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
// 创建控制面板
JPanel controlPanel = createControlPanel();
// 创建预览面板
previewPanel = createPreviewPanel();
mainPanel.add(controlPanel, BorderLayout.WEST);
mainPanel.add(previewPanel, BorderLayout.CENTER);
add(mainPanel);
setVisible(true);
}
private JPanel createControlPanel() {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setBorder(BorderFactory.createTitledBorder("卡片设置"));
panel.setPreferredSize(new Dimension(200, 400));
// 祝福语输入
panel.add(new JLabel("祝福语:"));
messageArea = new JTextArea(5, 15);
messageArea.setText("感恩节快乐!\n感谢你的一切!");
JScrollPane scrollPane = new JScrollPane(messageArea);
panel.add(scrollPane);
panel.add(Box.createRigidArea(new Dimension(0, 10)));
// 背景样式选择
panel.add(new JLabel("背景风格:"));
String[] backgrounds = {"温馨", "丰收", "简约", "传统"};
backgroundStyle = new JComboBox<>(backgrounds);
backgroundStyle.addActionListener(e -> updatePreview());
panel.add(backgroundStyle);
panel.add(Box.createRigidArea(new Dimension(0, 10)));
// 字体样式选择
panel.add(new JLabel("字体样式:"));
String[] fonts = {"默认", "手写", "优雅", "可爱"};
fontStyle = new JComboBox<>(fonts);
fontStyle.addActionListener(e -> updatePreview());
panel.add(fontStyle);
panel.add(Box.createRigidArea(new Dimension(0, 10)));
// 生成按钮
JButton generateBtn = new JButton("生成卡片");
generateBtn.addActionListener(e -> generateCard());
panel.add(generateBtn);
panel.add(Box.createRigidArea(new Dimension(0, 10)));
// 保存按钮
JButton saveBtn = new JButton("保存卡片");
saveBtn.addActionListener(e -> saveCard());
panel.add(saveBtn);
return panel;
}
private JPanel createPreviewPanel() {
JPanel panel = new JPanel(new BorderLayout()) {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
// 绘制背景
String bgStyle = (String) backgroundStyle.getSelectedItem();
if (bgStyle != null) {
drawBackground(g2d, bgStyle);
}
// 绘制装饰元素
drawDecorations(g2d);
}
};
panel.setBorder(BorderFactory.createTitledBorder("卡片预览"));
return panel;
}
private void drawBackground(Graphics2D g2d, String style) {
switch (style) {
case "温馨":
g2d.setColor(new Color(255, 228, 225)); // 粉红色
break;
case "丰收":
g2d.setColor(new Color(255, 218, 185)); // 桃色
break;
case "简约":
g2d.setColor(new Color(245, 245, 245)); // 浅灰色
break;
case "传统":
g2d.setColor(new Color(255, 239, 213)); // 奶油色
break;
}
g2d.fillRect(0, 0, getWidth(), getHeight());
}
private void drawDecorations(Graphics2D g2d) {
// 绘制简单的感谢装饰
g2d.setColor(new Color(139, 69, 19)); // 棕色
g2d.setFont(new Font("Serif", Font.BOLD, 40));
g2d.drawString("🦃", 50, 80);
g2d.drawString("🍁", 150, 100);
g2d.drawString("🌽", 250, 80);
}
private void updatePreview() {
previewPanel.repaint();
// 更新文字显示
Graphics2D g2d = (Graphics2D) previewPanel.getGraphics();
if (g2d != null) {
String fontType = (String) fontStyle.getSelectedItem();
String message = messageArea.getText();
Font font;
switch (fontType) {
case "手写":
font = new Font("Segoe Script", Font.PLAIN, 16);
break;
case "优雅":
font = new Font("Georgia", Font.ITALIC, 16);
break;
case "可爱":
font = new Font("Comic Sans MS", Font.BOLD, 16);
break;
default:
font = new Font("Serif", Font.PLAIN, 16);
}
g2d.setFont(font);
g2d.setColor(new Color(139, 69, 19));
// 绘制祝福语
String[] lines = message.split("\n");
int y = 120;
for (String line : lines) {
g2d.drawString(line, 50, y);
y += 25;
}
}
}
private void generateCard() {
// 生成并显示完成提示
updatePreview();
JOptionPane.showMessageDialog(this,
"🎉 感恩节卡片已生成!",
"生成成功",
JOptionPane.INFORMATION_MESSAGE);
}
private void saveCard() {
// 模拟保存功能
JOptionPane.showMessageDialog(this,
"💾 卡片已保存到桌面!",
"保存成功",
JOptionPane.INFORMATION_MESSAGE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new ThanksgivingCardGenerator();
});
}
}
案例5:感恩节倒计时器
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.util.Timer;
import java.util.TimerTask;
public class ThanksgivingCountdown {
private LocalDate thanksgivingDate;
private Timer timer;
public ThanksgivingCountdown() {
// 计算今年的感恩节(美国)
thanksgivingDate = calculateThanksgiving(2024);
timer = new Timer();
}
// 计算感恩节日期
private LocalDate calculateThanksgiving(int year) {
LocalDate novFirst = LocalDate.of(year, Month.NOVEMBER, 1);
int dayOfWeek = novFirst.getDayOfWeek().getValue(); // 1=周一
// 第1个周四的日期
int daysToFirstThursday = (4 - dayOfWeek + 7) % 7;
// 第4个周四(感恩节)
return novFirst.plusDays(daysToFirstThursday + 21);
}
// 获取倒计时信息
public String getCountdownInfo() {
LocalDate today = LocalDate.now();
Duration duration = Duration.between(
today.atStartOfDay(),
thanksgivingDate.atStartOfDay()
);
long days = duration.toDays();
if (days < 0) {
return "🎄 今年的感恩节已经过去了!\n明年请早哦!";
} else if (days == 0) {
return "🎉 今天就是感恩节!🎉\n感恩节快乐!";
} else {
long hours = duration.toHours() % 24;
long minutes = duration.toMinutes() % 60;
long seconds = duration.getSeconds() % 60;
return String.format(
"🦃 距离感恩节还有:%d天 %d小时 %d分钟 %d秒\n" +
"📅 感恩节日期:%s",
days, hours, minutes, seconds,
thanksgivingDate.format(DateTimeFormatter.ofPattern("yyyy年M月d日"))
);
}
}
// 获取感恩节建议
public String getThanksgivingTips() {
String[] tips = {
"🌟 提前计划菜单,确保所有食材都能买到",
"📝 列出需要感谢的人和事",
"🎁 准备一些感恩节小礼物",
"🍽️ 练习一下火鸡的烹饪技巧",
"📞 提前邀请家人朋友参加聚会",
"🎵 准备感恩节音乐播放列表",
"📷 准备相机记录美好时刻",
"🧹 提前打扫房屋,准备迎接客人"
};
LocalDate today = LocalDate.now();
Duration duration = Duration.between(
today.atStartOfDay(),
thanksgivingDate.atStartOfDay()
);
long days = duration.toDays();
if (days >= 0 && days < 30) {
int index = (int)(days % tips.length);
return "💡 感恩节小贴士:\n" + tips[index];
} else {
return "💡 可以开始规划感恩节了!\n" + tips[0];
}
}
// 启动实时倒计时
public void startRealTimeCountdown() {
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
System.out.print("\033[H\033[2J"); // 清除控制台
System.out.flush();
System.out.println("🎄 感恩节倒计时 🎄");
System.out.println("=" .repeat(40));
System.out.println(getCountdownInfo());
System.out.println();
System.out.println(getThanksgivingTips());
System.out.println("=" .repeat(40));
System.out.println("按 Ctrl+C 退出");
}
}, 0, 1000); // 每秒更新
}
public static void main(String[] args) {
ThanksgivingCountdown countdown = new ThanksgivingCountdown();
System.out.println("🎄 感恩节倒计时程序已启动 🎄");
System.out.println();
// 显示基本信息
System.out.println(countdown.getCountdownInfo());
System.out.println();
System.out.println(countdown.getThanksgivingTips());
// 询问是否启动实时倒计时
System.out.println("\n是否启动实时倒计时?(y/n)");
try {
int input = System.in.read();
if (input == 'y' || input == 'Y') {
countdown.startRealTimeCountdown();
}
} catch (Exception e) {
System.out.println("按任意键退出...");
}
}
}
运行说明
- 案例1:直接运行
ThanksgivingGreeting,会显示感恩节判断和祝福语 - 案例2:运行
GiftListManager,通过控制台交互管理礼物清单 - 案例3:运行
ThanksgivingRecipeManager,查看和管理感恩节食谱 - 案例4:运行
ThanksgivingCardGenerator,需要图形界面支持 - 案例5:运行
ThanksgivingCountdown,显示感恩节倒计时
这些案例展示了Java在不同场景下的应用:
- 面向对象编程:使用类、方法、封装
- 集合框架:ArrayList、HashMap的使用
- 日期时间处理:Java 8 的 LocalDate/LocalDateTime
- 文件/控制台交互:Scanner、System.in
- 图形界面:Swing组件
- 多线程/定时器:Timer、TimerTask
每个案例都融入了感恩节的主题元素,适合学习和参考,希望这些代码对您有帮助!