2 s123456m1 s123456m1 于 2016.05.05 20:18 提问

怎样用Calendar返回当前年份,程序如下

package yichang;

import java.sql.Date;
import java.util.Calendar;
import java.util.Scanner;

public class InsuranceCheck {
public static void BornYear(int bornyear)throws AgeException{
//why this way cannot use source with the file?
int years = 2016 - bornyear;

    if(years-16<0){
        throw new AgeException("年龄太小,不用保险!");
}
    if(years-16<4){
        throw new AgeException("需要缴纳2000元保险费!");
    }
    else{
        throw new AgeException("需要支付1000元保险费!");
    }


}

public static void main(String[] args) throws AgeException {
  Scanner sc=new Scanner(System.in);

// System.out.println("请输入出生年份:");
// String bornyear=sc.next();
try{
Calendar calendar = Calendar.getInstance();
Date dates = (Date) calendar.getTime();
BornYear(1996);
} catch(AgeException e){
System.out.println(e.getMessage());

 }
}

}

3个回答

yifanSJ
yifanSJ   2016.05.05 20:52
已采纳

public class InsuranceCheck {
public static void main(String[] args) throws Exception {
Calendar calendar = Calendar.getInstance();
Date dates = (Date) calendar.getTime();//Thu May 05 20:49:55 CST 2016
SimpleDateFormat sdf = new SimpleDateFormat("yyyy");//yyyy-MM-dd
String year = sdf.format(dates);
System.out.println(year);//2016
}
}

yifanSJ
yifanSJ   2016.05.05 20:53

public class InsuranceCheck {
public static void main(String[] args) throws Exception {
Calendar calendar = Calendar.getInstance();
Date dates = (Date) calendar.getTime();//Thu May 05 20:49:55 CST 2016
SimpleDateFormat sdf = new SimpleDateFormat("yyyy");//yyyy-MM-dd
String year = sdf.format(dates);
System.out.println(year);//2016
}
}

qq_34108945
qq_34108945   2016.05.05 22:24

直接用Calendar的方法get()可以得到
如:calendar.get(Calendar.YEAR);

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!