-2
public void sortNumberByAscending(int number1, int number2, int number3, int number4) {
    int first = 0;
    int second = 0;
    int third = 0;
    int fourth = 0;
    // Answer here


    //
    System.out.println("The numbers are: " + first + ", " + second + ", " + third + ", " + fourth);
}

public static void main(String[] args) { SortNumbers cr = new SortNumbers();

    cr.sortNumberByAscending(35, -4, 7, 6); // The numbers are: -4, 6, 7, 35
    cr.sortNumberByAscending(-1, 0, 18, -10); // The numbers are: -10, -1, 0, 18
    cr.sortNumberByAscending(1, 2, 3, 4); // The numbers are: 1, 2, 3, 4
}

For example: (35, -4, 7, 6); // The numbers are: -4, 6, 7, 35

1 Answers1

0

Can be done using Arrays.sort(int[] a), but that's probably not what you're supposed to do, however the question doesn't list any restrictions other than "no if statements", so this is a valid answer.

public static void sortNumberByAscending(int number1, int number2, int number3, int number4) {
    int[] arr = { number1, number2, number3, number4 };
    Arrays.sort(arr);
    System.out.println("The numbers are: " + Arrays.toString(arr));
}

Test

sortNumberByAscending(9, 3, 7, 4);

Output

The numbers are: [3, 4, 7, 9]
Andreas
  • 154,647
  • 11
  • 152
  • 247
  • At best a duplicate ? https://stackoverflow.com/questions/8938235/sort-an-array-in-java – Scary Wombat Mar 25 '20 at 01:48
  • @ScaryWombat Nah, because that article starts with "have array, need sorting", but this question is "have 4 numbers, need sorting", and with a restriction like "no if statement", I'm guessing that using `Arrays.sort()`, or any kind of array, is not truly a valid answer. Since we don't know what OP has learned, and hence what potential solutions are "available", we can only guess. I'm guessing that maybe ternary operators is the answer that is expected. Until we know more, I'm leery of closing as duplicate of anything. This answer is just to show *an* option, given lack of requirements. – Andreas Mar 25 '20 at 01:56
  • Understood. Not sure what they want. – Scary Wombat Mar 25 '20 at 01:59
  • @Andreas I have a confusion with the coding which you gave. Where are we using int first, second, third, fourth? In this question System.out.println is taking first, second, third and fourth integers instead of numbers – user13060550 Mar 26 '20 at 23:40
  • @user13060550 We're not using the `first`, `second`, `third`, and `fourth` local variables, because they are not needed with this solution. If you insist on having them, then add `first = arr[0]; second = arr[1]; third = arr[2]; fourth = arr[3];` after the call to `sort()`. – Andreas Mar 26 '20 at 23:45
  • @Andreas Thanks for your help. – user13060550 Mar 26 '20 at 23:50