如何在Java中自动将输入字符转换为大写
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21147319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert input char to uppercase automatically in Java
提问by matchaGerry
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 类来获取输入,并希望在显示时将输入转换为大写字母。这是我的代码
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
PS:字母“a”是我在终端输入的
However I want to it display as an uppercase one. How can I change it?
但是我希望它显示为大写字母。我怎样才能改变它?
采纳答案by rgettman
The toUpperCase
methoddoesn't change the value of the char
(it can't); it returns the uppercased char
. Change
该toUpperCase
方法不会改变char
(它不能)的值;它返回大写的char
. 改变
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.
更新后的问题现在表明将在键入时打印大写字符。Java 不能这样做,因为 Java 不控制 O/S 如何将用户输入回显到屏幕。我上面的解决方案只会产生额外的输出,即使它是大写的。
回答by zee
System.out.println(Character.toUpperCase(c));
System.out.println(Character.toUpperCase(c));
回答by fastcodejava
Since, java is pass by value, you need to use the return value. Either print Character.toUpperCase(c)
directly or set it to some var
.
由于java是按值传递的,因此您需要使用返回值。Character.toUpperCase(c)
直接打印或将其设置为 some var
。
回答by fastcodejava
Here Is An Example Of How You Can Change A Character To UpperCase.
这是如何将字符更改为大写的示例。
char ch;
字符 ch;
System.out.println("Input Characters:");
ch = (char) System.in.read();
System.out.println("Character Is: " + ch);
sc.nextLine();
System.out.println("Upper Case: " + Character.toUpperCase(ch));