华为od机考 生日礼物java代码
时间: 2023-08-09 22:02:58 浏览: 144
猜生日java代码
华为od机考生日礼物的Java代码可以是一个简单的程序,其中实现了一个生日礼物的功能。以下是一个可能的代码示例:
```java
import java.util.Scanner;
public class BirthdayGift {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入您的姓名:");
String name = scanner.nextLine();
System.out.println("请输入您的生日(格式:YYYY-MM-DD):");
String birthday = scanner.nextLine();
System.out.println("请输入当前日期(格式:YYYY-MM-DD):");
String currentDate = scanner.nextLine();
int age = calculateAge(birthday, currentDate);
String gift = chooseGift(age);
System.out.println(name + ",根据您的年龄,我们为您准备了一份生日礼物:" + gift);
}
private static int calculateAge(String birthday, String currentDate) {
// 解析生日和当前日期的年份、月份、日期
int birthYear = Integer.parseInt(birthday.substring(0, 4));
int birthMonth = Integer.parseInt(birthday.substring(5, 7));
int birthDay = Integer.parseInt(birthday.substring(8, 10));
int currentYear = Integer.parseInt(currentDate.substring(0, 4));
int currentMonth = Integer.parseInt(currentDate.substring(5, 7));
int currentDay = Integer.parseInt(currentDate.substring(8, 10));
// 根据年份、月份、日期计算年龄
int age = currentYear - birthYear;
if (currentMonth < birthMonth || (currentMonth == birthMonth && currentDay < birthDay)) {
age--;
}
return age;
}
private static String chooseGift(int age) {
if (age <= 12) {
return "一本绘本";
} else if (age <= 18) {
return "一本小说";
} else if (age <= 30) {
return "一支口红";
} else if (age <= 50) {
return "一本养生书籍";
} else {
return "一份健康体检套餐";
}
}
}
```
这段代码首先会要求用户输入姓名、生日和当前日期。然后,根据生日和当前日期的差值,计算出用户的年龄。最后,根据年龄选择适合的生日礼物,并输出给用户。根据年龄的不同,选择的礼物会有所差异。
阅读全文