1

I am trying to get a valid input of "y", "Y", "n" , or "N".

If the input is not valid (for example any word that starts with a "y" or "n") I want it to re-prompt the user for input.

So far I have:

while  (again.charAt(0) != 'N' && again.charAt(0) != 'n' && again.charAt(0) !='Y' && again.charAt(0) != 'y' ) {
    System.out.println ("Invalid Inpur! Enter Y/N");
    again = numscan.next();
}

if (again.charAt(0)== 'N' || again.charAt(0) == 'n') {
    active = false;                   
} else {
    if (again.charAt(0)== 'Y' || again.charAt(0) == 'y'){
        active = true;
        random = (int) (Math.random () *(11));
    }
}

The problem I am having is if I enter any word that starts with the letter "y" or "n" it senses it as valid input (since it is the character at slot 0). I need help fixing this so I can re-prompt the user when they enter a word that starts with a "y" or "n".

Thanks!

5 Answers 5

3

Assuming again is a string containing the complete user input, you could use:

while (!again.equals("N") && !again.equals("n") ...

The .equals() method will match only if the entire string matches.

Sign up to request clarification or add additional context in comments.

1 Comment

Remember that there is an equalsIgnoreCase method which could consolidate the condition of the while-loop.
3

You could just test to make sure the length of the input is 1:

again.length() == 1

But a better approach might be:

while (! (again.equalsIgnoreCase("n") || again.equalsIgnoreCase("y"))) {
    ...
}

or even

while (! again.matches("[nyNY]")) {
    ...
}

Comments

1

One of the way would be:

First check again String length is only ONE character. If not, ask again.

if(again.length() ==1)
{
 while  (again.charAt(0) != 'N' && again.charAt(0) != 'n' && again.charAt(0) !='Y' && again.charAt(0) != 'y' ) {
               System.out.println ("Invalid Inpur! Enter Y/N");
                again = numscan.next();
            }
.....

}else
     {
System.out.println ("Invalid Inpur! Enter Y/N");
                    again = numscan.next();
    }

Comments

1

It sounds like what you want is:

while  (!again.equals("N") && !again.equals("n") && !again.equals("Y") && !again.equals("y") ) {
    System.out.println ("Invalid Inpur! Enter Y/N");
    again = numscan.next();
}

This way you can also easily add Yes/No, etc later if you want.

Comments

0

Regex could be an alternative to have strict input checks. Following piece of code validates y or n ignoring the case.

while (!again.matches("(?i)^[yn]$")){
    System.out.println ("Invalid Inpur! Enter Y/N");
    again = numscan.next();
}
active = (again.equalsIgnoreCase("Y"))? true : false;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.