xVacuum - 3 months ago 8

Java Question

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`

`number`

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`

`5`

`9`

`19`

`27`

`18`

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

}

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

Source (Stackoverflow)

Comments