Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get exactly element in array?

Tags:

java

calendar

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;
}
like image 900
Peter Avatar asked Apr 18 '26 20:04

Peter


1 Answers

You would have to change the order of your array for this approach to work. Try

public static int getMinute(int no) {
    int num[] = {50, 40, 30, 20, 10, 0};
    for (int i = 0; i < num.length; i++) {
        if (no >= num[i]) {
            no = num[i];
            break;
        }
    }
    return no;
}
like image 134
Keppil Avatar answered Apr 21 '26 08:04

Keppil