简体   繁体   English

用函数简化 if 语句

[英]Simplify if statement with functions

I am working on a calendar project for a school seminar.我正在为学校研讨会做一个日历项目。 It is supposed to print three months that go after each other.它应该打印三个月的时间。 (You specify you want it to print January and it prints December of previous year, January and February). (您指定您希望它打印一月,它打印上一年的十二月、一月和二月)。

I have this if statement for this, but I would like to simplify it into three lines of code.我有这个 if 语句,但我想将它简化为三行代码。 How do I do it?我该怎么做? Is it possible?是否可以?

if (month == 1) {
    printMonth(12, year-1);
    printMonth(month, year);
    printMonth(month+1, year);
} else if (month == 12) {
    printMonth(month-1, year);
    printMonth(month, year);
    printMonth(1, year+1);
} else {
    printMonth(month-1, year);
    printMonth(month, year);
    printMonth(month+1, year);
}

Try using ternary operator :尝试使用三元运算符

printMonth(month == 1 ? 12 : month - 1, month == 1 ? year - 1 : year);
printMonth(month, year);
printMonth(month == 12 ? 1 : month + 1, month == 12 ? year + 1 : year);

You could use the Joda DateTime class to represent the current year/month, which is probably better than carrying years and month around as independent integers.您可以使用Joda DateTime 类来表示当前的年/月,这可能比将年和月作为独立整数携带更好。

Then you could write:然后你可以写:

printMonth(dt.minusMonths(1));
printMonth(dt);
printMonth(dt.plusMonths(1));

When I had such a problem myself, I tended to use an approach of combining year and month (also because I wanted to save some lines of code):当我自己遇到这样的问题时,我倾向于使用年月结合的方法(也是因为我想节省一些代码行):

int monthAndYear = year * 12 + month;

printMonth(monthAndYear - 1);
printMonth(monthAndYear);
printMonth(monthAndYear + 1);

As you can see, this requires you to adjust the printMonth method, if it is possible of course.如您所见,这当然需要您调整printMonth方法,如果可能的话。

private void printMonth(int monthAndYear) {
    int year = monthAndYear / 12;
    int month = monthAndYear % 12;
    // other code...
}

And these are still four lines though...虽然这些仍然是四行...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM