Home > Software design >  Intro Java: how to eliminate case sensitivity for user input here?
Intro Java: how to eliminate case sensitivity for user input here?

Time:06-10

If the user capitalizes, say, Capuchin, it works fine, but I'd like to eliminate case sensitivity. In my very limited experience, I'd look to place ".equalsIgnoreCase()" somewhere, but I can't figure out where it's possible to do that, or something similar. Do I need to change the method entirely or is there a way to do it within this block?

    String[]validSpecies = { "Capuchin", "Guenon", "Macaque", "Marmoset"};
    boolean isValid;

    System.out.println("Enter monkey's species: ");
    String species = scanner.nextLine();
    isValid = Arrays.asList(validSpecies).contains(species);
    if (!isValid) {
        System.out.println("This species is not permitted");
        return;
    }

CodePudding user response:

Normalize your list of valid species by storing them all in e.g. lowercase, and apply the same normalization on your user input. Regardless of the case of the user's input, you're checking whether a lowercase string (species.toLowerCase()) is within a set of lowercase valid species.

    String[]validSpecies = { "capuchin", "guenon", "macaque", "marmoset"};
    boolean isValid;

    System.out.println("Enter monkey's species: ");
    String species = scanner.nextLine();
    isValid = Arrays.asList(validSpecies).contains(species.toLowerCase());
    if (!isValid) {
        System.out.println("This species is not permitted");
        return;
    }

CodePudding user response:

Do it with a stream instead:

boolean isValid = Arrays.stream(validSpecies)
      .anyMatch(s -> s.equalsIgnoreCase(species));
  •  Tags:  
  • java
  • Related