问题描述
我尝试编译以下代码:
public static void main(String[] args){
for (char c = 'a'; c <='z'; c = c + 1) {
System.out.println(c);
}
}
当我尝试编译时,它抛出:
When I try to compile, it throws:
问题是,如果我写 c =(char)(c + 1)
,它确实可以工作, c + = 1
或 c ++
。
The thing is, it does work if I write c = (char)(c + 1)
, c += 1
or c++
.
我检查了当我尝试 char c = Character.MAX_VALUE + 1;
时,编译器会引发类似的错误,但是我看不到'c'的值可以传递'char'类型
I checked and the compiler throws a similar error when I try char c = Character.MAX_VALUE + 1;
but I see no way that the value of 'c' can pass 'char' type maximum in the original function.
推荐答案
c + 1
是 int
,因为操作数经过:
c + 1
is an int
, as the operands undergo binary numeric promotion:
-
c
是字符
-
1
是int
c
is achar
1
is anint
所以 c
必须是w标识为 int
以使其兼容添加;并且表达式的结果是 int
类型。
so c
has to be widened to int
to make it compatible for addition; and the result of the expression is of type int
.
对于工作的事物:
-
c =(char)(c + 1)
将表达式显式转换为char
,因此其值与变量的类型兼容; -
c + = 1
c =(字符)((c)+(1))
,因此与上一个基本相同。 -
c ++
char
,因此不需要强制转换。
c = (char)(c + 1)
is explicitly casting the expression tochar
, so its value is compatible with the variable's type;c += 1
is equivalent toc = (char) ((c) + (1))
, so it's basically the same as the previous one.c++
is of typechar
, so no cast is required.
这篇关于在Java中,如果“ char c ='a'”;为什么“ c = c + 1”?无法编译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!