Java基础练习(2019-03-11)

1.输入生日,计算年龄

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class test2 {
    public static void main(String[] args) {
        System.out.println("请输入出生年份:");
        Scanner sc = new Scanner(System.in);
        String birth = sc.next();
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
        Date date0 = null;
        try {
            date0 = sd.parse(birth);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Date date1 = new Date();
        //将两个Date类型转换为毫秒值。getTime()
        long time = date0.getTime();
        long time1 = date1.getTime();
        long res = (time1 - time) / 1000 / 60 / 60 / 24 / 365;

        System.out.println(res);

    }

}

2.使用for循环和迭代器遍历集合

import java.util.ArrayList;
import java.util.Iterator;

public class test3 {
    public static void main(String[] args) {
        ArrayList<String> stus = new ArrayList<>();
        stus.add("nezha");
        stus.add("wukong");
        stus.add("bajie");

        //for
        for (int i = 0; i < stus.size(); i++) {
            System.out.println(stus.get(i));
        }

        //增强for
        for (String str:stus
             ) {
            System.out.println(str);
        }

        //使用迭代器
        Iterator<String> iterator = stus.iterator();
        while (iterator.hasNext()){
            String res = iterator.next();
            System.out.println(res);
        }
    }
}

3 try catch finally 中return执行顺序

public class test4 {
    public static void main(String[] args) {
        int mtd = mtd();
        System.out.println(mtd);
    }

    public static int mtd(){
        try{
            return 1;
        }catch (Exception e){
            return 2;
        }finally {
            //如果finally有return,永远返回finally中的return
            return 3;
        }
    }
}

posted @ 2020-03-11 23:03  姚狗蛋  阅读(89)  评论(0编辑  收藏  举报