I have an array:
int num[] = {10, 20, 30, 40, 50};
I get current minute from Calendar and compare it with array above to get exactly element in array.
My code as following, after compare it often get first element, it’s not correct as my wish, pls help to correct me. Thanks
public static int getMinute(int no) {
int num[] = {10, 20, 30, 40, 50};
for (int i = 0; i < num.length;; i++) {
if (no >= num[i]) {
no = num[i];
break;
}
}
return no;
}
Here are two solutions (both working in the
0..59range):If your array is really
0, 10, 20, ..., 50you could just do:If you have more a more complex matching you could use a
TreeSetlike this:Just note that you would need to include a lower bound to get it to work, otherwise
TreeSet.lowermight returnnull.