Home > Back-end >  add elemets to array using { ? : }
add elemets to array using { ? : }

Time:12-17

    int res[] = new int[]{(num1< num2 ? num1, num2 : num2 , num1)};

I'm trying to insert two integers into an array! the element should be smaller and the second element should be larger. arrays.sort() not good idea!; simple old techniques are known I needed a new solution like ternary!

how do I need to inset two arrays while checking using the ternary operator? is this possible to use ternary in {} while adding elements into the array. does the compiler understand what I'm trying to do?

in eclipse I'm getting:

Multiple markers at this line

  • Syntax error on token ",", . expected
  • The primitive type int of num1 does not have a field num2
  • Syntax error on token ",", . expected

CodePudding user response:

try like this

int res[] = new int[]{Math.min(num1, num2), Math.max(num1, num2)};

CodePudding user response:

You can do either of this:

int res[] = new int[]{Math.min(num1, num2), Math.max(num1, num2)};

OR

int res[] = num1 < num2 ? new int[]{num1, num2} : new int[]{num2, num1};

CodePudding user response:

This could also work:

int[] res = new int[] {(a<b ? a : b), (a>b? a : b)};
  • Related