简体   繁体   中英

Java While-Loop Program

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!

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]")) {
    ...
}

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.

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();
    }

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM