Dylan Baldwin Dylan Baldwin - 1 month ago 6
Java Question

My Boolean evaluates to FALSE when I user an || OR or an && and in JAVA

The part

static boolean isBagFull = ((!Bag.itemSlot1.equals("Empty"))||(!Bag.itemSlot2.equals("Empty"))||(!Bag.itemSlot3.equals("Empty"))||(!Bag.itemSlot4.equals("Empty"))||(!Bag.itemSlot5.equals("Empty")));


always becomes FALSE! PLEASE HELP! although i checked all the itemSlots and they are all "Empty"

static Bag bag = new Bag();
static String helmet = "";
static String chestplate = "";
static String leggings = "";
static String boots = "";
static boolean isBagFull = ((!Bag.itemSlot1.equals("Empty"))||(!Bag.itemSlot2.equals("Empty"))||(!Bag.itemSlot3.equals("Empty"))||(!Bag.itemSlot4.equals("Empty"))||(!Bag.itemSlot5.equals("Empty")));


public void removeArmour(String s, int b){
if (b==1&&!helmet.equals("")) {
if (!isBagFull){//ITS USED HERE GUYS!!!!!!!!!!!!!!!!!! HELP!!!!!
bag.newItem(s);
helmet = "";
}else{
JOptionPane.showMessageDialog(null, "You do not have any room to remove the "+s);
}
}else if (b==2&&!chestplate.equals("")){
if (!isBagFull){
bag.newItem(s);
chestplate = "";
}else{
JOptionPane.showMessageDialog(null, "You do not have any room to remove the "+s);
}
}else if (b==3&&!leggings.equals("")){
if (!isBagFull){
bag.newItem(s);
leggings = "";
}else{
JOptionPane.showMessageDialog(null, "You do not have any room to remove the "+s);
}
}else if (b==4&&!boots.equals("")){
if (!isBagFull){
bag.newItem(s);
boots = "";
}else{
JOptionPane.showMessageDialog(null, "You do not have any room to remove the "+s);
}
}else if (b>=5||b<=0){
JOptionPane.showMessageDialog(null, "Sorry you don't have the correct position!", "ERROR", 0);
JOptionPane.showMessageDialog(null, "Helmet = 1 \n Chestplate = 2 \n Leggings = 3 \n Boots = 4", "Armour Numbers", 0);
}else{
JOptionPane.showMessageDialog(null, "You ar not wearing anything there!");
}
}

Answer

Since all itemSlots are "Empty" your condition:

 ((!Bag.itemSlot1.equals("Empty"))
||(!Bag.itemSlot2.equals("Empty"))
||(!Bag.itemSlot3.equals("Empty"))
||(!Bag.itemSlot4.equals("Empty"))
||(!Bag.itemSlot5.equals("Empty")));

evaluates to:

 ((!"Empty".equals("Empty"))
||(!"Empty".equals("Empty"))
||(!"Empty".equals("Empty"))
||(!"Empty".equals("Empty"))
||(!"Empty".equals("Empty")));

which evaluates to:

 ((!true)
||(!true)
||(!true)
||(!true)
||(!true));

It should be obvious why it's always false :)

Assuming your bag is full if any one slot is not empty, you really want:

static boolean isBagFull = ((Bag.itemSlot1.equals("Empty"))||(Bag.itemSlot2.equals("Empty"))||(Bag.itemSlot3.equals("Empty"))||(Bag.itemSlot4.equals("Empty"))||(Bag.itemSlot5.equals("Empty")));

But if it's only full if all slots are not empty, you want:

static boolean isBagFull = ((Bag.itemSlot1.equals("Empty"))&&(Bag.itemSlot2.equals("Empty"))&&(Bag.itemSlot3.equals("Empty"))&&(Bag.itemSlot4.equals("Empty"))&&(Bag.itemSlot5.equals("Empty")));
Comments