Problem with String Comparison Denial

Asked

Viewed 207 times

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 some mistake in this part:

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

Because I’m never getting out of the (while) loop. I’m making right the denial of comparison ?

(!opcaoSentar.equals("J")) || (!opcaoSentar.equals("C"))
  • You are aware that you will only leave if you type C or J higher ne?

  • Sure, but even if you type, you’re not leaving

  • Are you watching case sensitive? C != c, etc. Leer.next() is the console’s imput? What is in the Leer object?

2 answers

3

The correct is:

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

That reads:

while opcaoSentar is different from J and other than C

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

It is noteworthy that the equals is case sensitive, and the condition will only be validated if one of the letters is typed in uppercase. If this does not make much difference to condition, just change to String#equalsIgnoreCase():

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

3


The part with problem is this same:

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

Change 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 logic corrected, it is:

J    C    !J && !C
0    0    true
0    1    false
1    0    false
1    1    false

Browser other questions tagged

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