Peter
Peter

Reputation: 155

How to get exactly element in array?

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;
}

Upvotes: 3

Views: 125

Answers (3)

geby
geby

Reputation: 374

There's a superfluous semicolon in this line:

for (int i = 0; i < num.length;; i++) {

Removing it should fix the problem.

Upvotes: 2

dacwe
dacwe

Reputation: 43504

Here are two solutions (both working in the 0..59 range):

  1. If your array is really 0, 10, 20, ..., 50 you could just do:

    return 10 * (no / 10);
    
  2. If you have more a more complex matching you could use a TreeSet like this:

    TreeSet<Integer> c = new TreeSet<Integer>(Arrays.asList(0, 4, 23, 12, 41));
    
    System.out.println(c.lower(5));   // return 4
    System.out.println(c.lower(54));  // return 41
    System.out.println(c.lower(32));  // return 23
    

    Just note that you would need to include a lower bound to get it to work, otherwise TreeSet.lower might return null.

Upvotes: 2

Keppil
Keppil

Reputation: 46229

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;
}

Upvotes: 3

Related Questions