gpt4 book ai didi

java - 在java中如果 "char c = ' a' "why does "c = c + 1“无法编译?

转载 作者:行者123 更新时间:2023-12-01 22:41:07 25 4
gpt4 key购买 nike

我尝试编译以下代码:

public static void main(String[] args){
for (char c = 'a'; c <='z'; c = c + 1) {
System.out.println(c);
}
}

当我尝试编译时,它抛出:

Error:(5, 41) java: incompatible types: possible lossy conversion from int to char

问题是,如果我写 c = (char)(c + 1)c += 1c++ 它确实有效>.

我检查过,当我尝试 char c = Character.MAX_VALUE + 1; 时,编译器抛出了类似的错误,但我看不出“c”的值可以超过“char”类型最大值在原来的函数中。

最佳答案

c + 1 是一个 int,因为操作数经历 binary numeric promotion :

  • c 是一个 char
  • 1 是一个 int

所以c必须扩展为int以使其兼容加法;表达式的结果是int类型。

至于“有效”的事情:

  • c = (char)(c + 1) 显式地将表达式转换为 char,因此其值与变量的类型兼容;
  • c += 1 is equivalent to c = (char) ((c) + (1)),所以和上一个基本一样。
  • c++ is of type char,因此不需要强制转换。

关于java - 在java中如果 "char c = ' a' "why does "c = c + 1“无法编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53260641/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com