How to convert input char to uppercase automatically in Java

26,555

Solution 1

The toUpperCase method doesn't change the value of the char (it can't); it returns the uppercased char. Change

Character.toUpperCase(c);

to

c = Character.toUpperCase(c);

UPDATE

The updated question now indicates that the uppercased characters are to be printed as they're typed. Java cannot do that, because Java doesn't control how the O/S echoes user input to the screen. My solution above would only produce additional output, even if it is uppercased.

Solution 2

System.out.println(Character.toUpperCase(c));

Share:
26,555
matchaGerry
Author by

matchaGerry

Updated on July 09, 2022

Comments

  • matchaGerry
    matchaGerry almost 2 years

    I am using a Scanner class to get the input and want to convert the input to uppercase letter when display it. This is my code

    Scanner input = new Scanner(System.in);
    System.out.print("Enter a letter: ");
    char c = input.next().charAt(0);
    Character.toUpperCase(c);
    

    Since I have convert it to uppercase, but the output is like

    input: a
    c = A;
    output: Enter a letter: a
    

    PS: The letter "a" is what I typed in the terminal

    However I want to it display as an uppercase one. How can I change it?

  • Boris the Spider
    Boris the Spider over 10 years
    Not sure this is the problem. The OP wants the echo on the tty to automatically uppercase characters as they are typed.
  • matchaGerry
    matchaGerry over 10 years
    Yes, thanks a lot. But I am still wondering about the display of the input after changing my code.
  • Boris the Spider
    Boris the Spider over 10 years
    @matchaGerry sadly that is impossible from Java.
  • rgettman
    rgettman over 10 years
    @matchaGerry The TTY part was not evident from your question. Please update the question.
  • matchaGerry
    matchaGerry over 10 years
    @rgettman Ok I have updated it. Anyway, thank your answer it is a problem in my code.
  • matchaGerry
    matchaGerry over 10 years
    @BoristheSpider since you have told me that it is impossible from Java I think I need to change it when I type.