w2lf
w2lf

Reputation: 50

How can I check if all elements of array doesn't equal to some value? (e.g. not empty)

Array before.

  String[] player = {"Empty","Empty","Empty","Empty"}

Array after input.

String[] player = {"Tom","Bob","Alex","Kid"}

I remember there was a way to check all of the elements of the array.

if(!player[0].equals("Empty") && !player[1].equals("Empty") && !player[2].equals("Empty") && !player[3].equals("Empty"))
{
   System.out.println("No more space");
}

My question. Is there a way to select all of the elements of an array?

Upvotes: 0

Views: 2562

Answers (3)

om-nom-nom
om-nom-nom

Reputation: 62835

I know this might not be an option, but in Java 8 you could do:

boolean nonEmpty = Arrays.asList(player).anyMatch(x -> x.equals("Empty"))

Upvotes: 1

Juvanis
Juvanis

Reputation: 25950

You can iterate over the array implicitly:

if(!Arrays.asList(player).contains("Empty"))
   System.out.println("No more space.");

or iterate over the array explicitly:

for(String p : player)
{
    if(!p.equals("Empty"))
       continue;
    else
    {
       System.out.println("No more space.");
       break;
    }
}

Upvotes: 0

Taha Paksu
Taha Paksu

Reputation: 15616

You mean something like:

boolean hasEmpty = false;

for (int i = 0; i < player.length(); i ++)
{
     if(player[i].equals("Empty")){
         hasEmpty = true;
         break;
     }
}

if(hasEmpty) System.out.println("No more space");

Upvotes: 1

Related Questions