定义一个JDate类,成员变量包括year、month和day,成员员方法包括input_Date( )和output_Date( )实现日期的输入和输出。在main()方法中创建该类的对象并访问这些方法
时间: 2024-10-15 20:09:32 浏览: 74
要定义一个名为`JDate`的类,用于表示日期,我们可以使用Java的内置`java.time.LocalDate`类作为基础。如果你想自定义一个简单的日期类,你可以这样做:
```java
import java.util.Scanner;
public class JDate {
private int year;
private int month;
private int day;
// 构造器
public JDate(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
// 输入日期的方法
public void input_Date() {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入年份:");
this.year = scanner.nextInt();
System.out.println("请输入月份(1-12):");
this.month = scanner.nextInt();
System.out.println("请输入日期(1-31):");
this.day = scanner.nextInt();
scanner.close();
}
// 输出日期的方法
public void output_Date() {
System.out.printf("日期: %d-%02d-%02d\n", year, month, day);
}
// 主方法
public static void main(String[] args) {
JDate dateObj = new JDate(0, 0, 0); // 初始化日期为某个默认值
// 访问input_Date方法进行输入
dateObj.input_Date();
// 访问output_Date方法输出日期
dateObj.output_Date();
}
}
```
在这个例子中,`JDate`类有三个私有成员变量`year`、`month`和`day`,分别代表年、月和日。`input_Date()`方法用于从用户处获取输入,而`output_Date()`方法则用于打印当前的日期。
在`main()`方法中,我们创建了一个`JDate`对象并调用这两个方法。你可以根据实际需求修改这个示例,例如添加错误检查或处理异常。
阅读全文
相关推荐
![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)
![](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)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)