Java Challenge - FindXInOrder

Hello everyone,

I’m trying to solve the FindXInOrder challenge in Java, but I’m not succeeding.

My code is:

import java.util.Arrays;
class FindXInOrder {

  public static int getX(int x, int[] nums) {
    // Primero hay que ordenar los numeros de menor a mayor.
    int y = x - 1;
    Arrays.sort(nums);
    // Ahora hay que encontrar el numero del indice que piden.
    Integer number = nums[y];
    return number;
    }
    
  public static void main(String[] args) {
    int nums[] = new int[]{ 12, 3, 5, 7, 4, 19, 26};
    int x = 3;
    System.out.print(getX(x, nums));
  }
}```

When I test the code, this is what the machine tells me:

Tests failed to run due to an error: “4”. Check your code and try again.


Any ideas?

Thanks!

does it do the same thing if you do

int number = nums[y];

instead of

Integer number = nums[y];

?

I thought the challenge was to do this without using .sort

Also, maybe a default return is needed, like if the array has a length of 0,
then 0 should be returned.

1 Like

Thanks for your help.

I’ve implemented what you said, but the result is the same:

import java.util.Arrays;
class FindXInOrder {

  public static int getX(int x, int[] nums) {
    // Primero hay que ordenar los numeros de menor a mayor.
    int y = x - 1;
    if(nums.length == 0){
    return y = 0;
    }
    Arrays.sort(nums);
    // Ahora hay que encontrar el numero del indice que piden.
    int number = nums[y];
    return number;
  }
    
  public static void main(String[] args) {
    int nums[] = new int[]{ 12, 3, 5, 7, 7, 4, 19, 26};
    int x = 4;
    System.out.print(getX(x, nums));
  }
}

The outcome of running test is:

Tests failed to run due to an error: "4". Check your code and try again.

I tested your code,
I think the problem is about edge cases for parameter x
(meaning dealing with invalid values for x).

Here’s what I did to attempt to fix that:

    if ((x < 1) || (x > nums.length)) {
      return 0;
    }

Also,

you don’t need the y = after return
That should be
return 0;