Problem with String Negation

1

A part of my code:

// faça: 
do {
    System.out.println("Você deseja sentar na Janela (J) ou Corredor (C) ?");
    opcaoSentar = leer.next();
    // se a opção foi J
    if (opcaoSentar.equals("J")) {
        System.out.println("Venda Efetivada");
        // Preenchendo o lugar com 1
        janela[numeroPoltronaSolicitado - 1] = 1;
        // se não, se o a opção for C  
    } else if (opcaoSentar.equals("C")) {
        System.out.println("Venda efetivada");
        // preenchendo o lugar com 1
        corredor[numeroPoltronaSolicitado - 1] = 1;
    } else {
        // caso n foi nenhuma, opção invalida e vai voltar a pergunta
        // por causa do {do while}
        System.out.println("Opção Invalida !");
    }

    // enquanto a opção de sentar (Janela ou Corredor) for diferente de C ou J    
} while ((!opcaoSentar.equals("J")) || (!opcaoSentar.equals("C")));

I think there's something wrong with this part:

while ((!opcaoSentar.equals("J")) || (!opcaoSentar.equals("C")));

Because I can not ever get out of the loop. Am I doing the denial of the comparison right?

(!opcaoSentar.equals("J")) || (!opcaoSentar.equals("C"))
    
asked by anonymous 07.04.2017 / 23:53

2 answers

3

The problem snippet is this:

while ((!opcaoSentar.equals("J")) || (!opcaoSentar.equals("C")));

Switch to:

while ((!opcaoSentar.equals("J")) && (!opcaoSentar.equals("C")));

Because according to the truth table:

J    C    !J || !C
0    0    true
0    1    true
1    0    true
1    1    false    

It would only be false if it was 'J' and 'C' at the same time! With the corrected logic, it stays:

J    C    !J && !C
0    0    true
0    1    false
1    0    false
1    1    false
    
08.04.2017 / 00:03
3

The correct one is:

while ((!opcaoSentar.equals("J")) && (!opcaoSentar.equals("C")));

That reads:

  

while opcaoSentar is different from J and than C

After all, you want the operation to end if one of the two options is typed, and as it is, the only way out of the loop is to be equal to both, which theoretically is impossible.

It should be noted that equals is case sensitive , and the condition will only be validated if one of the letters is capitalized. If this does not make much difference to the condition, just switch to String#equalsIgnoreCase() :

while ((!opcaoSentar.equalsIgnoreCase("J")) && (!opcaoSentar.equalsIgnoreCase("C")));
    
08.04.2017 / 00:03