0

The are several subjects on Ternary Operator as here:

Ternary Operator - JAVA

Except that, I don't understand the syntax.

I have a method with an if and an else.

public static void affichage(String[] tabPersonnage, int[] tabAge, boolean[] tabSexe){

    for(int i=0; i<tabPersonnage.length; i++){
      System.out.println("Personnage n° " + (i+1));
      System.out.println("Pseudo : " + tabPersonnage[i]);
      System.out.println("Age : " +  tabAge[i] + " ");
      if(tabSexe[i]){
        System.out.println("Sexe : Homme ");
      } else {
        System.out.println("Sexe : Femme ");
      }
      System.out.println("-------------------");
    }

  }

The syntax for the ternary operator is

condition ? instruction1 : instruction2

I tried this:

public static void affichage(String[] tabPersonnage, int[] tabAge, boolean[] tabSexe){

    for(int i=0; i<tabPersonnage.length; i++){
      System.out.println("Personnage n° " + (i+1));
      System.out.println("Pseudo : " + tabPersonnage[i]);
      System.out.println("Age : " +  tabAge[i] + " ");
      System.out.println("Sexe : " + ((tabSexe[i])  ? "Homme": "Femme")));
      System.out.println("-------------------");
    }

  }

I have an error message => error: ';' expected

  • 3
    Typo. One too many `)`. It should be `System.out.println("Sexe : " + ((tabSexe[i]) ? "Homme" : "Femme"));` – Elliott Frisch Mar 28 '21 at 14:12
  • 2
    That's because you have unbalanced parentheses. It's not specific to the conditional operator ("the ternary operator" is a bad name, it just means "the operator with 3 operands") – user15187356 Mar 28 '21 at 14:12

1 Answers1

0

change

System.out.println("Sexe : " + ((tabSexe[i])  ? "Homme": "Femme")));

to

System.out.println("Sexe : " + (tabSexe[i] ? "Homme": "Femme"));
XMehdi01
  • 5,538
  • 2
  • 10
  • 34