Page 151 - Introduction to Programming with Java: A Problem Solving Approach
P. 151

                response "q"
qq
⇒false response.equals("q") ⇒true
So what can you do to solve this problem? In Chapter 3, you learned to use the equals method to test strings for equality. The equals method compares the string objects pointed to by the memory addresses. In the above picture, the string objects hold the same sequence of characters, q and q, so the method call, response.equals("q"), returns true, which is what you want. Here’s the corrected code fragment:
if (response.equals("q") || response.equals("Q"))
4.5 || Logical Operator 117
      {
}
System.out.println("Bye");
response == "q"
Or as a more compact alternative, use the equalsIgnoreCase method like this: if (response.equalsIgnoreCase("q"))
{
}
System.out.println("Bye");
A third alternative is to use the String class’s charAt method to convert the string input into a character and then use the == operaAtorptoacogmpoare thPatDchFaractEer wnith tahenchcaraecter literals, ‘q’ and ‘Q’:
char resp = response.charAt(0);
if (resp == 'q' || resp == 'Q')
{
}
System.out.println("Bye");
               These implementations are not trivial translations from the pseudocode that specified the algorithm. It’s important to organize your thoughts before you start writing Java code. But even very good preparation does not eliminate the need to keep thinking as you proceed. Details matter also!
Errors
The devil is in the details.
    We made a big deal about not using == to compare strings because it’s a very easy mistake to make and it’s a hard mistake to catch. It’s easy to make this mistake because you use == all the time when comparing primitive values. It’s hard to catch this mistake because programs that use == for string comparison com- pile and run with no reported errors. No reported errors? Then why worry? Because although there are no reported errors, there are still errors—they’re called logic errors.
   A logic error occurs when your program runs to completion without an error mes-
sage, and the output is wrong. Logic errors are the hardest errors to find and fix because
there’s no error message glaring at you, telling you what you did wrong. To make matters
worse, using == for string comparison generates a logic error only some of the time, not all of the time. Because the logic error occurs only some of the time, programmers can be lulled into a false sense of confi- dence that their code is OK, when in reality it’s not OK.
Be careful. Test every aspect.
       





































































   149   150   151   152   153