温故知新Java篇(二)

目录

1.时间处理

2.类

3.工厂方法

4.生成0-9随机数


1.时间处理

LocalDate类,比Date类简便

    void dateOperation(){
        LocalDate today=LocalDate.now(); //返回当前日期
        LocalDate date2=LocalDate.of(2023,1,6); //返回指定日期

        //当前月制作日历
        System.out.println("Mon Tue Wen Thu Fri Sat Sun");
        LocalDate temp=today.minusDays(today.getDayOfMonth()-1); //获取1号
        for (int i=0;i<temp.getDayOfWeek().getValue()-1;i++) //第一行缩进
        System.out.print("    ");

        while(temp.getMonthValue()== today.getMonthValue()){ //不超过当前月
            System.out.printf("%3d",temp.getDayOfMonth()); //打印日期
            if (temp.getDayOfMonth()== today.getDayOfMonth())
                System.out.print("*");  //当天日期标星号
            else
                System.out.print(" ");

            if (temp.getDayOfWeek().getValue()==7)  //到周日就加一个换行
                System.out.println();
            temp=temp.plusDays(1);
        }
    }

//            Mon Tue Wen Thu Fri Sat Sun
//                                      1
//              2   3   4   5   6*  7   8
//              9  10  11  12  13  14  15
//             16  17  18  19  20  21  22
//             23  24  25  26  27  28  29
//             30  31

2.类

构造函数可重载,用getter和setter封装

自动回收,不支持析构器

若要避免null值,1.为无参构造器赋值或直接在字段上赋值;2.限制含参构造器的值

可使用代码块(构造对象时运行)static代码块(运行一次),但尽量不用。

    public HelloDomain(Integer id,String name){
       this.id= Objects.requireNonNull(id,"cannot be null!");//严格型,产生异常
       this.name=Objects.requireNonNullElse(name,"unknown");//宽松型
    }

3.工厂方法

将方法的构造装进其它类或接口的方法中,便于提示或分类。

//接口,便于提示继承者
public interface Things {
    void show();
    static Books getBooks(){
        return new Books();
    }
    static Cats getCats(){
        return new Cats();
    }
}

//便于分类
public class LivingThings {
   public static Cats getCats(){
       return new Cats();
   }
}

//两个具体类
public class Books implements Things{
    @Override
    public void show() {
        System.out.println("books");
    }
}

public class Cats implements Things {

    @Override
    public void show() {
        System.out.println("cats");
    }
}

        //测试
        void factoryMethod(){
        Things book=Things.getBooks();
        book.show();
        Things cat= LivingThings.getCats();
        cat.show();
        }
        //books
        //cats

4.生成0-9随机数

    void randomNum(){
        var x= new Random();
        int y= x.nextInt(10);
        System.out.println(y);
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值