java 一句代码获取当前季节

因为本人遇到和季节相关的业务,需要获取当前季节,去网上搜了几个代码。但是代码行数实在太多,在此奉献本人浓缩的一句java代码获取当前季节。方便大家复制到自己的代码中,献丑了。

System.out.println(Calendar.getInstance().get(Calendar.MONTH)==0?"winter":Calendar.getInstance().get(Calendar.MONTH)==1?"spring":Calendar.getInstance().get(Calendar.MONTH)==2?"spring":Calendar.getInstance().get(Calendar.MONTH)==3?"spring":Calendar.getInstance().get(Calendar.MONTH)==4?"summer":Calendar.getInstance().get(Calendar.MONTH)==5?"summer":Calendar.getInstance().get(Calendar.MONTH)==6?"summer":Calendar.getInstance().get(Calendar.MONTH)==7?"autumn":Calendar.getInstance().get(Calendar.MONTH)==8?"autumn":Calendar.getInstance().get(Calendar.MONTH)==9?"autumn":Calendar.getInstance().get(Calendar.MONTH)==10?"winter":Calendar.getInstance().get(Calendar.MONTH)==11?"winter":"");

虽然用一句话完成了,但是代码看起来臃肿,只是用了匿名对象。后来经过优化到2行代码,封装成一个方法。

public  String getSeason(){
    int seasonNumber = Calendar.getInstance().get(Calendar.MONTH);
    return seasonNumber>=1&&seasonNumber<=3?"春":seasonNumber>=4&&seasonNumber<=6?"夏":seasonNumber>=7&&seasonNumber<=9?"秋":seasonNumber>=10?"冬":"冬";
        }

初来乍到,尽情的喷我吧!

你可能感兴趣的:(javase)