#Replacing null values in an array
1 messages · Page 1 of 1 (latest)
While you are waiting for getting help, here are some tips to improve your experience:
If nobody is calling back, that usually means that your question was not well asked and hence nobody feels confident enough answering. Try to use your time to elaborate, provide details, context, more code, examples and maybe some screenshots. With enough info, someone knows the answer for sure.
Don't forget to close your thread using the command </help-thread close:1027500463647621170> when your question has been answered, thanks.
I have a function that's supposed to take in values and replace any null values in an array with these values. If there are no null values, then it shouldn't replace anything.
Everything works fine, except that when it runs out of null values it still replaces index 0 of the array with a value. The reason that happens is because the .orElse(0) directs it to index 0, but I can't get rid of it or else none of it works.
public void pickUp(String val){
int null_index;
null_index = IntStream.range(0, inventory.length)
.filter(i -> inventory[i] == null)
.findFirst()
.orElse(0);
inventory[null_index] = val;
Detected code, here are some useful tools:
public void pickUp(String val) {
int null _index;
null _index = IntStream.range(0, inventory.length).filter(i -> inventory[i] == null ).findFirst().orElse(0);
inventory[null _index] = val;
instead of orElse you can use ifPresent to check if the optional returned by findFirst() has a value and perform an operation with said value.
For example:
findFirst().ifPresent(index -> array[index] = values);
there Arrays.stream if u didn't knew
Thanks guys. I got it working like this:
public void pickUp(String val){
for (int i = 0; i < inventory.length; i++){
if (inventory[i] == null){
inventory[i] = val;
return;
}
}
}
Detected code, here are some useful tools:
public void pickUp(String val) {
for (int i = 0; i < inventory.length; i++) {
if (inventory[i] == null ) {
inventory[i] = val;
return ;
}
}
}