Doubt with logical treatment of two strings

Asked

Viewed 57 times

1

I am with a basic java problem, I have been researching on logical treatment of strings within an IF condition, but I did not find the answer to my problem:

if (!"y".equals(resposta) || !"n".equals(resposta)) {
    System.out.println("REPOSTA INVÁLIDA!");
    return;
}

The program asked the user to write if he wants to continue, (yes - y or no - n), so if the answer is DIFFERENT from "y" or "n", he will give the warning inside the if block, but the condition is not working for the string "n", only for the string "y".

  • 2

    Assuming the user presses n then he makes the comparison !"y".equals(resposta) that will be true as the operator || is short circuit for truth the JVM abandons the tests in the first true because if I continued I would make the comparison !"n".equals(resposta) that will be false and would end with true || false that is true given to Truth table of disjunction. How to test if it meets both conditions use a conjunction if (!"y".equals(resposta) && !"n".equals(resposta)).

  • 1

    Oh yes, I went for a while without programming and forgot the difference of "or" and "and", thanks for the answer ;D

1 answer

5


From the logical point of view you want to capture all answers that are not equal to y or equal to n.

if (!("y".equals(resposta) || "n".equals(resposta))) {
    System.out.println("REPOSTA INVÁLIDA!");
    return;
}

The difference is subtle, the negation applies to disjunction as a whole and not to each individual condition. In other words, you want to NÃO(x OU y), which is logically different from NÃO x ou NÃO y.

For de Morgan laws you can also rewrite this condition in a simplified way like:

if (!"y".equals(resposta) && !"n".equals(resposta))) {
    System.out.println("REPOSTA INVÁLIDA!");
    return;
}

I mean, you want all the answers that aren’t y and are also not n; i and.., NÃO y E NÃO n. Behold commenting of Augusto Vasques for more details on this solution.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.