我在 int 到 char 转换方面遇到了一个奇怪的问题。这是我的代码:
char a=100;
System.out.println(a);
System.out.println(a+1);
System.out.println();
System.out.println((char)a+1);
System.out.println((char)101);
System.out.println( (char)a+1==(char)101 );
它给了我这个输出:
d
101
101
e
true
这绝对是奇怪的:两个不同的输出在比较时似乎是相同的!为什么会这样呢?以及如何制作a+1
被视为字符?
感谢您的回答,如果有一些英语错误,我很抱歉,这不是我的母语。
最佳答案
在这种情况下
System.out.println((char)a+1);
您只是将a
转换为char
(它已经是了)。加法使整个表达式成为一个 int
,因此重载的 PrintWriter#println(int)
被执行。为了将其视为 char
,请执行
System.out.println((char) (a+1));
The binary + operator performs addition when applied to two operands of numeric type, producing the sum of the operands.
The type of an additive expression on numeric operands is the promoted type of its operands.
Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:
If either operand is of type double, the other is converted to double.
Otherwise, if either operand is of type float, the other is converted to float.
Otherwise, if either operand is of type long, the other is converted to long.
Otherwise, both operands are converted to type int.
关于Java int 转 char 输出真的很奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19479857/