我正在为圣诞节制作临期日历,需要使用switch语句。我最大的困惑是,每一天都会有一个特别为那一天设计的新班级。我正在研究google和stack overflow能提供什么。我想知道有没有别的办法来压缩这个?
public void onClick(View v) {
//Calculate the days between (date - 12/7/20)
LocalDate dateBefore = java.time.LocalDate.now();
LocalDate dateAfter = LocalDate.of(2020, Month.DECEMBER, 25);
int daysAway = (int) ChronoUnit.DAYS.between(dateBefore, dateAfter);
switch(daysAway){
case 24:
openDay1();
break;
case 23:
openDay2();
break;
case 22:
openDay3;
break;
case 21:
openDay4;
break;
case 20:
openDay5;
break;
case 19:
openDay6;
break;
case 18:
openDay7;
break;
case 17:
openDay8;
break;
case 16:
openDay9;
break;
case 15:
openDay10;
break;
case 14:
openDay11;
break;
case 13:
openDay12;
break;
case 12:
openDay13;
break;
case 11:
openDay14;
break;
case 10:
openDay15;
break;
case 9:
openDay16;
break;
case 8:
openDay17;
break;
case 7:
openDay18;
break;
case 6:
openDay19;
break;
case 5:
openDay20;
break;
case 4:
openDay21;
break;
case 3:
openDay22;
break;
case 2:
openDay23;
break;
case 1:
openDay24;
break;
case 0:
openChristmas;
break;
default:
notTime.start();
break;
}
}
我知道这是一个巨大的混乱,这就是我试图修复!我很感激你能给我的任何反馈!
2条答案
按热度按时间mf98qq941#
ncgqoxb02#
使用java 14开关表达式语法:
由于代码非常简单,只需将其折叠到一行:
使用java 8方法引用数组(注意顺序颠倒):
既然你说过“每个(daysaway)案例都会打开一个为那一天设计的新类”,那么就使用一个接口(例如。
Runnable
)以及类文字数组:您还可以动态地构建类名(没有数组或
switch
声明):