0

I want to check that 2 of 5 fields are filled, but I don't know how.

If I put this in conditions, that only checks one of the conditions is true:

OR

  • field1 is not empty
  • field2 is not empty
  • field3 is not empty
  • field4 is not empty
  • field5 is not empty

there is an easier way that the following?

  • field1 is not empty
  • field2 is not empty

OR

  • field1 is not empty
  • field3 is not empty

OR

  • field1 is not empty
  • field4 is not empty

OR

  • field1 is not empty
  • field5 is not empty

OR

  • field2 is not empty
  • field3 is not empty

OR

  • field2 is not empty
  • field4 is not empty (...)
Stephan Muller
  • 27,018
  • 16
  • 85
  • 126

2 Answers2

1

2 For loops

    for(int i=0;i<5;i++){
     for(int j=i+1;j<5;j++){
      if(field[i]==true&&field[j]==true)
       return true;
     }
    }

EDIT: You replace the statements for your needs. And you must store the fields in an array. Credits to zolyboy for the i+1 thing :)

Roberto Anić Banić
  • 1,411
  • 10
  • 21
  • j variable should start from i not from 0 – Zolyboy Jan 27 '14 at 13:00
  • why to test field[1] == true && field[2] == true and after that field[2] == true && field[1] == true ? it's totally the same thing, if you put instead of 0 i+1 then you will not do the same multiple times – Zolyboy Jan 27 '14 at 19:41
0

In SQL I would to it this way:

select if(if(field1='',0,1)+ if(field2='',0,1)+ if(field3='',0,1)+ if(field4='',0,1)+ if(field5='',0,1)=2) true else false end ...

In other language it could be something like:

int a = (field1.equals(""))0:1;
int b = (field2.equals(""))0:1;
int c = (field3.equals(""))0:1;
int d = (field4.equals(""))0:1;
int e = (field5.equals(""))0:1;

boolean result= (a+b+c+d+e==2)?true:false;

With above code you can easily use it for 3 of 5, 4 of 5, 7 of 10 conditions etc...

Cedric Simon
  • 4,571
  • 4
  • 40
  • 52