用java,idea软件,声明一个学生类,包括name、sex、birthday;showStudent()可以打印学生的姓名、性别和实际周岁年龄
时间: 2024-06-10 12:08:43 浏览: 112
好的,这是一个关于Java编程的问题,我很乐意回答你。以下是声明学生类的Java代码:
```java
public class Student {
private String name; // 学生姓名
private String sex; // 学生性别
private Date birthday; // 学生出生日期
// 构造函数
public Student(String name, String sex, Date birthday) {
this.name = name;
this.sex = sex;
this.birthday = birthday;
}
// 获取学生姓名
public String getName() {
return name;
}
// 获取学生性别
public String getSex() {
return sex;
}
// 获取学生实际周岁年龄
public int getAge() {
Calendar now = Calendar.getInstance();
Calendar birth = Calendar.getInstance();
birth.setTime(birthday);
int age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR);
if (now.get(Calendar.MONTH) < birth.get(Calendar.MONTH)
|| (now.get(Calendar.MONTH) == birth.get(Calendar.MONTH)
&& now.get(Calendar.DAY_OF_MONTH) < birth.get(Calendar.DAY_OF_MONTH))) {
age--;
}
return age;
}
// 打印学生信息,包括姓名、性别和实际周岁年龄
public void showStudent() {
System.out.printf("学生姓名:%s,学生性别:%s,学生实际周岁年龄:%d岁\n", name, sex, getAge());
}
}
```
在这个学生类中,我们包含了学生的姓名、性别和出生日期属性。我们在构造函数中将这些属性初始化,并提供了获取属性值和打印学生信息的方法。在获取实际周岁年龄的方法中,我们使用Calendar类计算学生的年龄。最后,在showStudent()方法中,我们输出学生的信息,其中包括姓名、性别和实际周岁年龄。
如果你想使用IDEA软件测试这段代码,你可以在一个新的Java项目中创建一个名为"Student"的类,然后复制粘贴上面提供的代码。接着,在main()方法中实例化一个Student对象并调用showStudent()方法即可:
```java
public static void main(String[] args) {
Student student = new Student("Tom", "男", new Date(1999, 0, 1));
student.showStudent(); // 输出:"学生姓名:Tom,学生性别:男,学生实际周岁年龄:22岁"
}
```
当然,你也可以根据自己的需求修改这段代码。希望这可以帮助到你。
阅读全文
相关推荐
![java](https://img-home.csdnimg.cn/images/20250102104920.png)
![java](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)