-3

private int nColumns = 1;

public void onClick(View view) {

            nColumns = nColumns == 1 ? 2 : 1; //Cannot understand this line. 

Could anyone please explain?

alkas
  • 1,446
  • 1
  • 11
  • 11

2 Answers2

1

It is a ternary operator. The part (nColumns == 1) ? 2 : 1; basically means if nColumns is equal to 1 then the first one, 2, is selected and else the latter, 1. That value is then stored in the same variable nColumns.

So if it is equal to 1 then it gets 2 else it gets 1.

It does the same as the following:

if(nColumns == 1)
  nColumns = 2;
else
  nColumns = 1;
niklassc
  • 597
  • 1
  • 9
  • 24
-1

if the number of nColumns is 1 return 2 else return 1 and assign it to it slef which is nColumns.

if(nColumns==1)
   nColumns=2;
else
   nColumns=1;