xVacuum xVacuum - 3 months ago 8
Java Question

Finding closest integer from an array which is rounded up

I'm not good at english so title can be confusing.

What i'm trying to do:

I have a int array

10, 20, 30
and I want to take numbers from it based on
number
variable

if
int number = 10;


I want the result from the "method" to be
20


if
int number = 21;


i want the result to be
30


I don't know how to explain this properly, but I hope it's understandable.




What is this for? I have a player inventory which can has different sizes
9, 18, 27, 36, 45, 54
and I have a item contents which is for example
5
. So I want to have inventory size
9
. If the item content size was
19
, inventory size should be
27
, not
18
. And that's my problem.




I tried a lot of different iterations, calculations but every attempt was very unsuccesful.
I had this method to get a closest value from an array, but i don't know how to change it to round up.

public int getClosestInteger(int value, int[] numbers) {
int distance = Math.abs(numbers[0] - value);
int id = 0;
for (int i = 1; i < numbers.length; i++){
int dist = Math.abs(numbers[i] - value);

if(dist < distance){
id = i; distance = dist;
}
}
return numbers[id];
}


How I can do that?

Answer

If I understand your question correctly, this should work:

public int getClosestInteger(int value, int[] numbers) {
    for (int i = 0; i < numbers.length; i++){
        if(value < numbers[i]){
            return numbers[i];
        }
    }
}
Comments