haca haca - 1 month ago 8
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);
while(scan.hasNext()){
String temp=scan.next();
if(temp.matches("[ˆa-zA-Z]+")){
temp.toLowerCase();
System.out.print(temp + " ");
}
}
sc.close();


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

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

Answer

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:

[^a-zA-Z]

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 + " ");
}