一道简单的java编程题? 10
编写程序实现下列功能:定义一个满足下列要求的Date类:(1)用日/月/年的格式输出日期;(2)设置日期操作;(3)求该日是该年的第几天。再定义一个主类,在主类的main...
编写程序实现下列功能:
定义一个满足下列要求的Date类:
(1)用日/月/年的格式输出日期;
(2)设置日期操作;
(3)求该日是该年的第几天。
再定义一个主类,在主类的main()方法中创建两个Date类的对象,分别为两个对象设置不同的日期,分别输出两个对象的日期,并分别求出两个对象的日期是该年的第几天 展开
定义一个满足下列要求的Date类:
(1)用日/月/年的格式输出日期;
(2)设置日期操作;
(3)求该日是该年的第几天。
再定义一个主类,在主类的main()方法中创建两个Date类的对象,分别为两个对象设置不同的日期,分别输出两个对象的日期,并分别求出两个对象的日期是该年的第几天 展开
1个回答
展开全部
import java.text.ParseException;
import java.text.SimpleDateFormat;
//日期类
public class Date {
private String year;
private String month;
private String day;
public Date(String year, String month, String day) {
this.year = year;
this.month = month;
this.day = day;
}
public void format(){
System.out.println(day + "/" + month + "/" + year);
}
public void calculate(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
try {
java.util.Date startDate = sdf.parse(year + "/" + "01" + "/" + "01");
java.util.Date inputDate = sdf.parse(year + "/" + month + "/" + day);
long resultDay = (inputDate.getTime() - startDate.getTime())/(24 * 1000 * 60 * 60);
System.out.println("第" + (resultDay + 1) + "天");
} catch (ParseException e) {
e.printStackTrace();
}
}
}
//测试类
public class Test {
public static void main(String[] args) {
Date date1 = new Date("2020","04","11");
Date date2 = new Date("2020","01","02");
date1.format();
date1.calculate();
date2.format();
date2.calculate();
}
}
import java.text.SimpleDateFormat;
//日期类
public class Date {
private String year;
private String month;
private String day;
public Date(String year, String month, String day) {
this.year = year;
this.month = month;
this.day = day;
}
public void format(){
System.out.println(day + "/" + month + "/" + year);
}
public void calculate(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
try {
java.util.Date startDate = sdf.parse(year + "/" + "01" + "/" + "01");
java.util.Date inputDate = sdf.parse(year + "/" + month + "/" + day);
long resultDay = (inputDate.getTime() - startDate.getTime())/(24 * 1000 * 60 * 60);
System.out.println("第" + (resultDay + 1) + "天");
} catch (ParseException e) {
e.printStackTrace();
}
}
}
//测试类
public class Test {
public static void main(String[] args) {
Date date1 = new Date("2020","04","11");
Date date2 = new Date("2020","01","02");
date1.format();
date1.calculate();
date2.format();
date2.calculate();
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询