-1

I have created a do-loop to continue iterating until the user enters a word starting with Y or N, originally using a primitive check on a char and now using the methods outlined below to check strings for equality. With both comparison media, I found that even with 'y' or 'n' entered, the loop would not exit. I cannot explain why, and hope that you can:

The following is the code:

            do{
            System.out.println("Please Enter a Valid y/n Reply:");
            eraseOr_no = histScanner.next();
            if(histScanner.hasNext()){
                (eraseOr_no.replaceAll("\\s+", "")).toLowerCase();
                character = Character.toString(eraseOr_no.charAt(0));

                //DEBUGGING
                System.out.println("CHECKPOINT 5" + "----" + character);
                //DEBUGGING

            }
        }while(!(character.equals("n")) || !(character.equals("y")));

As is clear I have used a simply system to inform me of the value of the String character, and as you may be able to see it is successfully displaying the 'y' or 'n' meaning that my first-letter-retrieval code is functioning, though the entire do structure is not.

Continue
Answer:

CHECKPOINT 4.0.
PLACEHOLDER

Please Enter a Valid y/n Reply:
y
y
CHECKPOINT 5----y
Please Enter a Valid y/n Reply:
y
CHECKPOINT 5----y
Please Enter a Valid y/n Reply:
n
CHECKPOINT 5----y
Please Enter a Valid y/n Reply:
y
CHECKPOINT 5----n
Please Enter a Valid y/n Reply:

Should I try to remove all whitespace? Am I missing something more fundamental?

Wouter J
  • 41,455
  • 15
  • 107
  • 112
William Brun
  • 353
  • 2
  • 17

2 Answers2

2

You're saying:

while (character is not n) or (character is not y)

At least one of those conditions will always be true! If it's n then it's not y, and if it's y then it's not n (and if it's neither then both conditions are satisfied).

You probably want:

while (!(character.equals("n") || character.equals("y")))
arshajii
  • 127,459
  • 24
  • 238
  • 287
1

Your condition is wrong. It is either:

while(!(character.equals("n")) && !(character.equals("y"))); // A

or,

while(!(character.equals("n") || character.equals("y"))); // B

In words, this is, either:

(not "n") and (not "y")         //A

or:

neither "n" nor "y"        //B

Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287