Unexpected value type using conditional statements

Viewed 42

I'm trying to rewrite the following method using conditional statements instead of if-else statements I get the error unexpected value type required: variable found: value with "? left = 0 : left" and "? right = state[i + 1] : right" underlined. What am I doing wrong?

public class Automaton
{
    public void update()
    {
        // Build the new state in a separate array.
        int[] nextState = new int[state.length];
        // Naively update the state of each cell
        // based on the state of its two neighbors.
        for(int i = 0; i < state.length; i++) {
            int left, center, right;
            /*if(i == 0) {
                left = 0;
            }
            else {
                left = state[i - 1];
            }*/
            i == 0 ? left = 0 : left = state[i - 1];
            center = state[i];
            i + 1 < state.length ? right = state[i + 1] : right = 0;
            /*if(i + 1 < state.length) {
                right = state[i + 1];
            }
            else {
                right = 0;
            }*/
            nextState[i] = (left + center + right) % 2;
        }
        state = nextState;
    }
}
1 Answers

Please modify your code to:

left = i == 0 ? 0 : state[i - 1];
right =  i + 1 < state.length ?  state[i + 1] : 0;

See more about ternary-operator

Related