JAVA 无法从 int 转换为 short

Rób*_*rai 2 java int short

嗨,我是新来的,这是我的第一个问题:我有一个带有简单算术运算符的代码。但它不会工作:

int a = 10;
short premennaTypuShort = (short)a;     /*retyped variable a into short type and entered into new variable*/
premennaTypuShort = premennaTypuShort - 7;
/*now i am trying to decrease the number but eclipse wrote that cannot convert from int to short.*/
Run Code Online (Sandbox Code Playgroud)

我正在尝试减少指定为 short 的数字,但 eclipse 写的无法从 int 转换为 short。我不明白为什么。那么问题出在哪里呢?我该如何修复这个错误?

小智 5

java是32位的。这意味着无论何时执行任何算术运算,它都会以 32 位值返回。因此,您必须再次将其转换为 short,如下所示:

int a = 10;
short premennaTypuShort = (short)a;    
premennaTypuShort =(short)(premennaTypuShort - 7);
Run Code Online (Sandbox Code Playgroud)