
急求一道JAVA题~!从键盘输入一个日期,计算150天后的年Y、月M、日D和星期E。
急需答案~~只是JAVA入门的一道题,不要写得太深奥看不懂哈~ 答案满意另加悬赏! 展开
import java.util.*;
import java.text.*;
public class Dateceshi{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
boolean flag = true ;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
while(flag){
System.out.println("输入日期格式为yyyy年MM月dd日,输入@退出");
String str = sc.nextLine();
if(!"@".equals(str)){
try{
Date d = sdf.parse(str);
Calendar cd = Calendar.getInstance();
cd.setTime(d);
cd.add(Calendar.DAY_OF_YEAR ,150);
int year = cd.get(cd.YEAR);
int month = cd.get(cd.MONTH)+1;
int day_of_month = cd.get(cd.DAY_OF_MONTH);
int day_of_week = cd.get(cd.DAY_OF_WEEK) - 1 ;
if(day_of_week==0){
day_of_week += 7 ;
}
System.out.println("150天后: "+year+"年"+month+"月"+day_of_month+"日 星期"+day_of_week);
}catch(Exception e){
System.out.println("输入格式不正确!");
}
}else{
flag = false;
}
}
}
}

2023-06-12 广告
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Date now;
int year, month, day;
System.out.print("请输入一个日期(yyyy-mm-dd):");
try{
String temp = scan.next();
year = Integer.parseInt(temp.substring(0,4)); //临到4位年
month = Integer.parseInt(temp.substring(5,7)); //得到2位月
day = Integer.parseInt(temp.substring(8,10)); //得到2位天
now = new Date(year-1900, month-1, day); //构造日期对象
day = now.getDate() + 150; //增加150天
now = new Date(now.getYear(), now.getMonth(), day); //重新构造新的日期对象
System.out.println("150天以后:" + now.toLocaleString());
}
catch(Exception e){
e.printStackTrace();
}
}
}
需要注意的是,输入日期必须采用类似“2011-05-01”的格式,月份和天数必须为两位,如果只有一位,则左边补零;年份必须是4位。