Java中Switch-case语句,case⼀个范围、区间,使⽤三⽬运
算符解决!
java中的 switch-case 开关语句,⼤家应该都不陌⽣。
常见的是使⽤⽅式是这样的:
switch (clock) {
case 1:
System.out.println(1);
break;
case 2:
System.out.println(2);;
break;
case 3:
System.out.println(3);
break;
default :
System.out.println(100);
break;
}
但有时候因为业务需要,需要根据⼀个范围去进⾏操作,那该怎么办呢?
此时⽤到了三⽬运算符,相等于多个if-else嘛。只是看起来简洁⼀些。
这⾥我创建了⼀个临时变量(temp),利⽤三⽬表达式将范围值变为具体值,这样只需更改问号之后的值即可。
使⽤&⽽不使⽤&&,是因为&&前的表达式如果不成⽴,&&后⾯的表达式就不会执⾏。
⽽&前后的表达式都会执⾏,&和&& 都⼀样 前后表达式都为true 则为true;
则根据⾃⼰的业务灵活运⽤。
/**
* 根据传⼊的分钟 1~1440,将对应的时间段+1
* @param localTime
*/
public void setClockPushOne(int localTime) {
int temp = 0;
int clock = localTime>=temp&localTime<(temp+=60)?0:
localTime>=temp&localTime<(temp+=60)?1:
localTime>=temp&localTime<(temp+=60)?2:
localTime>=temp&localTime<(temp+=60)?3:
localTime>=temp&localTime<(temp+=60)?4:
localTime>=temp&localTime<(temp+=60)?5:
localTime>=temp&localTime<(temp+=60)?6:
localTime>=temp&localTime<(temp+=60)?7:
localTime>=temp&localTime<(temp+=60)?8:
localTime>=temp&localTime<(temp+=60)?9:
localTime>=temp&localTime<(temp+=60)?10:
localTime>=temp&localTime<(temp+=60)?11:
localTime>=temp&localTime<(temp+=60)?12:
localTime>=temp&localTime<(temp+=60)?13:
localTime>=temp&localTime<(temp+=60)?14:
localTime>=temp&localTime<(temp+=60)?15:
localTime>=temp&localTime<(temp+=60)?16:
localTime>=temp&localTime<(temp+=60)?17:
localTime>=temp&localTime<(temp+=60)?18:
localTime>=temp&localTime<(temp+=60)?19:
localTime>=temp&localTime<(temp+=60)?20:
localTime>=temp&localTime<(temp+=60)?21:
localTime>=temp&localTime<(temp+=60)?21:
localTime>=temp&localTime<(temp+=60)?22: localTime>=temp&localTime<=(temp += 60) ? 23 :100;
switch (clock) {
case 0:
++zero_and_one;
break;
case 1:
++one_and_two;
break;
case 2:
++two_and_three;
break;
case 3:
++three_and_four;
break;
case 4:
++four_and_five;
break;
case 5:
++five_and_six;
break;
case 6:
++six_and_seven;
break;
case 7:
++seven_and_eight;
break;
case 8:
++eight_and_nine;
break;
case 9:
++nine_and_ten;
break;
case 10:
++ten_and_eleven;
break;
case 11:
++eleven_and_twelve;
break;
case 12:
++twelve_and_thirteen;
break;
case 13:
++thirteen_and_fourteen;
break;
case 14:
++fourteen_and_fifteen;
break;
case 15:
++fifteen_and_sixteen;
break;
case 16:
++sixteen_and_seventeen;
break;
case 17:
++seventeen_and_eighteen;
break;
case 18:
++eighteen_and_nineteen;
break;
case 19:
++nineteen_and_twenty;
switch case判断字符串break;
case 20:
case 20:
++twenty_and_twenty_one;
break;
case 21:
++twenty_one_and_twenty_two;
break;
case 22:
++twenty_two_and_twenty_three;
break;
case 23:
++twenty_three_and_zero;
break;
default:
throw new RuntimeException("clock transform error"); }
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论