0

why I can't use continue with The ? : Operator :

public class TestArray {

public static void main(String[] args) {
  double[] myList = {1.9, 2.9, 3.4, 3.5};

  // Print all the array elements
  for (int i = 0; i < myList.length; i++) {
     System.out.println(myList[i] + " ");
  }


  // Finding the largest element
  double max = myList[0];
  for (int i = 1; i < myList.length; i++) {
     myList[i] > max ? max = myList[i] : continue ;
  }
  System.out.println("Max is " + max);  
}
} 
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
  • This is not how ternary operators work. They are meant to shorten conditional assignment, rather than condense code paths. – cs95 Jul 04 '17 at 18:19
  • Ternary if expects a return value, which `continue` does not provide. – luizfzs Jul 04 '17 at 18:20
  • 1
    Because that operator expects **expressions** for both cases. Continue is not an expression that can be evaluated to result in a **value**! – GhostCat Jul 04 '17 at 18:27
  • 1
    But also, the conditional operator is not a statement expression: even if you had an expression as the third operand, that code would not compile. – Andy Turner Jul 04 '17 at 19:55
  • If you don't know how to use ternary operators and get errors. Advice is to learn that first or use if else instead. max = myList[i] > max ? myList[i] : max; – Sunny Jul 05 '17 at 13:04

3 Answers3

1

The ternary operator does not function like that. It is used to return one of two values depending on a boolean expression.

x = statement ? value1 : value2

If that is not what you want then use a simple if else statement. Just replace with:

for (int i = 1; i < myList.length; i++) {
    if(myList[i] > max)
        max = myList[i]
}

If you want you can also have a look at .max():

Arrays.stream(myList).max()

and a bit more on how it works in: Java 8 stream's .min() and .max(): why does this compile?

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
0

Ternary operator works like this method:

public static <R> R ternaryOperator(boolean condition, R onTrue, R onFalse) {
    if (condition == true) {
        return onTrue;
    } else {
        return onFalse;
    }
}

Do you think you can write something like this?

ternaryOperator(myList[i] > max, max = myList[i], continue)
matoni
  • 2,479
  • 21
  • 39
-2

Use a normal if statement because a ternary operator returns a value.

msanford
  • 11,803
  • 11
  • 66
  • 93
Ben
  • 673
  • 3
  • 11