How to convert from tenerary (conditional operator) to if/else statement

if(board[j][i] > 0) {
  fill(board[j][i] ==1?255:0, board[j][i] ==2?255:0,0); 
  ellipse (i * bs, j * bs, bs, bs); 

--How would I go about changing this to an if else statement instead of the '?'

Tagged:

Answers

  • edited March 2018 Answer ✓

    there are TWO tenerarys:

    • board[j][i] ==1?255:0

    • board[j][i] ==2?255:0

    Both ask essentially :

    • Is board[j][i] == 1 then return 255 else return 0

    • Is board[j][i] == 2 then return 255 else return 0

    Both resulting values are used in a fill statement.

    In a 2D grid (chess board) that leads to different colors based on the value of board[j][i]

    New version:

    if(board[j][i] > 0) {     
    
        int redValue=0;
        int greenValue=0; 
    
        if(board[j][i] == 1)
            redValue=255;
            else 
            redValue=0;
    
        if(board[j][i] == 2)
            greenValue=255;
            else 
            greenValue=0;
    
    
        fill(redValue,greenValue,0); 
    
        ellipse (i * bs, j * bs, 
              bs, bs);
    
    }// if
    
  • For more on understanding the ternary operator, see, the reference page:

    ...and a wikipedia example...

Sign In or Register to comment.