0

Why does the boolean conditions like condition always return true ? Even if the variable reponse is equal to constants OUI or NON;

       final String OUI = "O";
       final String NON = "N";
       String reponse = OUI;
       // some code was omitted
       do {
        // some code was omitted

       // true
       boolean condition = false;

       do {
           System.out.println(MSG_SOL_TRONCON);
           reponse = mScanner.nextLine();
           // Debug
           System.out.println("Reponse:" + reponse + ":fin");
           /*
           // Boucle infinie, problème avec la condition
           // Infinite Loop
           condition = !((reponse == NON) || (reponse == OUI));
           System.out.println("Condition : " + condition);
           if (condition) {
               System.out.println(MSG_ERR_TRONCON);
           } // if
           */
       } while(condition);

    } while (reponse != NON);
charlesfranciscodev
  • 303
  • 1
  • 7
  • 17
  • 2
    Try `!NON.equals(response)`. Don't us `==` or `!=` with strings. See.http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java – bradimus Feb 08 '16 at 03:41

1 Answers1

0

On the line where you have

condition = !((reponse == NON) || (reponse == OUI));

you need to fix this condition to use string equality checks. == only works when comparing numerical values and most primitive data types. Since strings are a separate class and non-primitive data type, you must use string methods to check for equality. Thus like @bradimus was saying, you need something like

condition = !((response.equals(NON) || (response.equals(OUI));

instead, since .equals is a string method

Here's the function documentation: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#equals%28java.lang.Object%29

  • 1
    `NON.equals(response) ` is preffered over `response.equals(NON)`. It is `null` safe. – bradimus Feb 08 '16 at 03:58
  • @bradimus not necessarily. Many people would argue that "null safety" just hides bugs by not warning you when nulls get where they're not supposed to. – Louis Wasserman Feb 08 '16 at 04:28