Search code examples
javaeclipsejava.util.scanneruppercaselowercase

I need to ask for a 'Case in-sensitive' code for scanner input. any advice accepted


I wondered: is there a way to make the reading of scanner input 'case in-sensitive' whitout lower or upper case? I have to make lots of 'Y' or 'N' answers and I have to convert each scanner input to String, and then using '.toUpperCase' '.toLowerCase'. I feel like I'm missing something more practical...

My other idea was to create a scanner class that converts every input to string and then to Upper/LowerCase, but my question is basically if there is any way to set that from start that I might be missing...

public void acariciar(ArrayList<Animal> animales) {
    System.out.println("Quiere acariciar a estos animales?? Y ó N");

    String inputDeUsuario = escaner.nextLine();
    if (inputDeUsuario.toUpperCase().equals("Y")) {
        for (Animal animal : animales) {
            animal.acariciado();
        }
    }
}

Solution

  • There is no such thing as "case insensitive input" - a Latin letter is inherently either uppercase or lowercase. But you can ask for the comparison to ignore the case differences between each character pair of the strings being compared, with String.equalsIgnoreCase():

    inputDeUsuario.equalsIgnoreCase("Y")
    

    (If you are in a situation where you don't control the equality comparison, e.g. if you're adding strings to a HashSet, you're doing it the right way: pick either lowercase or uppercase, and convert everything to that case.)