0

I have a do While loop as follow:

do{
      System.out.println("Enter customer type (r/c/t): ");
      customerType = sc.next();
   }
   while(customerType !="r");

I am expecting the program to loop as long as I don't type r when the program prompts me so. However the program still loops when I type r, I am not sure why, hope someone can help. Thank you.

Sor
  • 11
  • 3
  • 1
    1. Don't compare Strings using `==` or `!=`. Use the `equals(...)` or the `equalsIgnoreCase(...)` method instead. Understand that `==` checks if the two *objects* are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. So `while(!"r".equals(customerType));` 2. Probably better to use `sc.nextLine()` – Hovercraft Full Of Eels Nov 19 '14 at 07:12
  • Hi Hovercraft Full Of Eels, thanks for the reply. '!"r".equals(customerType)' works fine, but what if I want to check for 3 different types of values, and if it's not one of these three, than loop like this: while (!"r".equals(customerType) || !"c".equals(customerType) || !"t".equals(customerType)) unfortunately this doesn't work – Sor Nov 19 '14 at 07:45
  • Sor, this has nothing to do with String equivalence and all to do with basic logic since that statement of yours above will **always** be true since `a` will **always** be either `!b` or `!c` if b and c are mutually exclusive. This is simple logic -- use a Venn diagram to see what I mean, and how you should fix this. (hint, it's your use of `||` -- again think it through). – Hovercraft Full Of Eels Nov 19 '14 at 15:01

0 Answers0