xVacuum xVacuum - 1 year ago 67
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

int number = 10;

I want the result from the "method" to be

int number = 21;

i want the result to be

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
. So I want to have inventory size
. If the item content size was
, inventory size should be
, not
. 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 Source

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];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download