简体   繁体   中英

How do you test the value of charAt(0)?

So I am writing a code that ask a user if they would like to be recommended a new pet. I give them a message dialog the ask them to enter Y for Yes and N for No. This is my code do far and there is something I am not getting. The big question is how do I test if the value they entered is Y or N. The answer they give can either be lower case or upper case. How do I code this?

public static void aPet()
{
    char answer;
    String newPet;
    newPet = JOptionPane.showInputDialog(null,"Would you like to recommend another pet?(Y), or Stop (N)","Another Recommendation?", JOptionPane.QUESTION_MESSAGE);
    answer = newPet.charAt(0);
    if (answer == y || answer == Y)
    {
        //methods to recommend pet
    }
        if (answer == n || answer == N)
        {
            System.exit(-1);
        }
}

You need to use actual character literals, not just the letter:

if (answer == 'y' || answer == 'Y')

Characters are denoted in code by surrounding the letter with single quotes (they can also be denoted in other ways, but this is the simplest).

You can read about this on The Java Tutorials > Primitive Data Types which says, among other things:

Always use 'single quotes' for char literals and "double quotes" for String literals.

You are missing single quotes around the values 'y' and 'n' :

Try this:

char answer = newPet.charAt(0);
if('y' == answer || 'Y' == answer) {
    // recommend pet
} else {
    // exit
}

OR

Edited

if(newPet.matches("y|Y")) {
    // recommend pet
} else {
    // exit
}

OR

if("y".equalsIgnoreCase(newPet)) {
    // recommend pet
} else {
    // exit
}

You can use Character#toUpperCase() like that:

if (Character.toUpperCase(answer) == 'Y')
{
    //methods to recommend pet
}

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