mardi 25 février 2020

JAVA How will an IF statement evaluate if || (OR) as well as && (AND) are placed in the same if statement

Currently I am working on a little personal project to help myself learn about coding. I'm wondering for future reference if I can combine logical operators of different types in a single if statement.

For example if I had

if (n == 0 || n == 1 && m == 0 || m == 1) {
  doSomething();
}

Would it check if either parts of the left side are true, then if either parts of the right are true, or would it do something similar to checking if both of the middle ones are true?

Does using parenthesis change anything For example

if ((n == 0 || n == 1) && (m == 0 || m == 1)) {
  doSomething();
}

Edit: From a suggestion I tried it out, but when i put three variables it started acting weird Here's my test:

int n = 1;
int m = 1;
int o = 1;

if (n == 0 || n == 1 && m == 0 || m == 1 && o == 0 || o == 1) {
  System.out.println("True");
}
else {
  System.out.println("False");
}

if ((n == 0 || n == 1) && (m == 0 || m == 1) && (o == 0 || o == 1)) {
  System.out.println("True");
}
else {
  System.out.println("False");
}

if all of them are 1 or 0, they both evaluate true, if n or m is not 1 or 0 the top evaluates true but the bottom does not.

However if o is not 0 or 1 both of them are false. I have found that parenthesis do in fact make a difference, but I can't quite tell why it's acting the way it is.

Aucun commentaire:

Enregistrer un commentaire