gpt4 book ai didi

java - 为什么我得到类型不匹配 : cannot convert from int to byte

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:49:56 24 4
gpt4 key购买 nike

class Test
{
public static void main(String[] args)
{
byte t1 = 111;
byte t2 =11;
byte t3 = t1+t2;

System.out.println(t1+t2);

}
}

在 Eclipse 中它显示错误 cannot convert from int to byte。这里的总和是 122,它在字节范围内。所以为什么我在这里得到这个错误。

提前致谢...

最佳答案

当您对字节进行数学运算时,Java 会扩大(自动类型提升)到字节(隐式向上转换)到整数这种情况。所以当你执行

 byte t3 = t1+t2; //  t1+t2; will be evaluated as integer.

由于 t1+t2 结果比 byte 宽,因此您需要将其向下转换为 byte。

消除编译错误。

 byte t3 = (byte) (t1+t2); // typecast to byte

更多信息请阅读JLS 5.1.2

关于java - 为什么我得到类型不匹配 : cannot convert from int to byte,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16633534/

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