为什么我收到不兼容的类型错误?

时间:2017-02-12 10:00:43

标签: java

我正在学习java并创建一些带有注释的简单测试程序,我收到一个错误,说“不兼容的类型:从int到short的可能有损转换”,short short = val5 + val6;我看起来这个错误意味着我正在尝试将一个int值放入一个短变量,但我在短片中存储的值只有27,所以我对于什么是错误我有点困惑。

public class test{
    public static void main(String[] args){
        double val1=4;
        float val2=9;
        long val3=30;
        int val4= 8;
        short val5= 15;
        short val6=12;
        byte val7=20;
        short shortVal= val5 + val6; //why the error here?
    }
}

2 个答案:

答案 0 :(得分:1)

short + short的结果有点矛盾,int。因此,您尝试将int分配给short变量(shortVal)。

答案 1 :(得分:1)

short + short会产生int。您需要int变量来存储结果:

int shortVal = val5 + val6;
相关问题