目录
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);
}