java – Compare both uppercase and lowercase answer to a question using "equals"

Question:

I am doing an exercise in java and I have to compare the entered answer:

do you wish to continue? y / n:

It must contemplate both s and S

I need to run it with only one answer

Answer:

You can solve this by using the equalsIgnoreCase () check, which compares the string against an object, ignoring case. It will return true if the compared strings are equivalent (case insensitive). Otherwise it will return false.

Example:

if("s".equalsIgnoreCase(respuesta)){
     //gestionas si es "si"
}else{
     //gestionas si es "no"
}

Another alternative would be to use the toLowerCase () function as indicated by partner @ lois6b, which converts all characters in the string to lowercase.

Example:

if("s".equals(respuesta.toLowerCase())){
     //gestionas si es "si"
}else{
     //gestionas si es "no"
}
Scroll to Top