57

I have an if statement:

if (inventory.contains("bread"))

But now I want to check

  • if inventory contains "bread"
  • but does not contain "water".

How can I do this?

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Tizer1000
  • 894
  • 2
  • 8
  • 19

4 Answers4

72

It seems that Luiggi Mendoza and joey rohan both already answered this, but I think it can be clarified a little.

You can write it as a single if statement:

if (inventory.contains("bread") && !inventory.contains("water")) {
    // do something
}
informatik01
  • 16,038
  • 10
  • 74
  • 104
Itsan Alias
  • 840
  • 8
  • 8
  • As per clean code principle ! should be avoided in conditions. Ideal would be to extract !inventory.contains( ingredient ) should be extracted to a separate method e.g. boolean inventoryDoesNotHave(ingredient) – antnewbee Jun 22 '23 at 07:55
6

Maybe

if (inventory.contains("bread") && !inventory.contains("water"))

Or

if (inventory.contains("bread")) {
    if (!inventory.contains("water")) {
        // do something here
    } 
}
informatik01
  • 16,038
  • 10
  • 74
  • 104
joey rohan
  • 3,505
  • 5
  • 33
  • 70
0

For your questions, use below

if(inventory.contains("bread") && !inventory.contains("water")) {

System.out.println("Bread is there and water not there");

}

else{

System.out.println("Both or any one condition not met");

}

Another example: Just use ! sign before contains function.

like if you want to perform some action, like if list does contains say stack then add stack.

   if (!list.contains("stack")) {
        list.add("stack");
    }`

or another method, if index of search string is -1,

 if(list.indexOf("stack")==-1){
    list.add("stack");

}

Ashish Gupta
  • 105
  • 1
  • 5
0

I know we can use the '!' to get the opposite value of the String.contains() function. If you do not want to use the '!' symbol, use the following code:

if(inventory.contains("bread"))
{
    if(inventory.contains("water"))
    {
        //do nothing
    }
    else
    {
        //do what you intend to do
    }
}
Sardaar54
  • 1
  • 3