简体   繁体   中英

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?

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");

我知道这可能不是一个选项,但在Java 8中你可以做到

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

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM