Search code examples
javabooleanuppercase

Taking in uppercase and lower case alphabet character


I am trying to figure out how I can accept user input in both upper and lowercase letters in the code below. My application takes in a string of the user's name and I need to be able to let them know if the character is in there regardless of capitalization.

boolean p=str.contains("R");
if(p)
System.out.println("string contains the char 'R'");
else
System.out.println("string does not contains the char 'R'");

Solution

  • You can simple convert your input by invoking toUpperCase() which will return a string in all upper case letters and then apply contains on the returned type

    boolean p = str                // robot
                   .toUpperCase()  // ROBOT
                   .contains("R"); // ROBOT contains R? true/false
    // note: value of str is still robot as original
    

    although if you don't need p more than once then no need to perform another character check then

    if(str.toUpperCase().contains("R"))
        System.out.println("string contains the char 'R'");
    else
        System.out.println("string does not contains the char 'R'");