haca haca - 1 year ago 66
Java Question

toLowerCase() Not finding Uppercase Character Using Scanner

Any ideas why the function .toLowerCase() isn't picking up my input in the string:
"This this 123 fff this This"?

Scanner scan=new Scanner(System.in);
String temp=scan.next();
System.out.print(temp + " ");

Expected Output is: "this this fff this this".

Output is this: "This this fff this This".

Answer Source

You need to actually assign the output from the call to toLowerCase() back to the temp variable:

if (temp.matches("[ˆa-zA-Z]+")) {
    temp = temp.toLowerCase();
    System.out.print(temp + " ");

Note that your character range [ˆa-zA-Z], while doing what you want is probably not what you think it is. I think you intended to write this:


which would match one or more characters which are not letters. But somehow you got this character (ˆ) in the range instead, which effectively makes your class match any letter plus this strange character. So, in the end, my answer should work for you, but you would be better off using this code:

if (temp.matches("[a-zA-Z]+")) {
    temp = temp.toLowerCase();
    System.out.print(temp + " ");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download