这个程序为什不能编译?怎样修改,怎样设置负值?The following method does not compile. Can you suggest w
这个程序为什不能编译?怎样修改,怎样设置负值? The following method does not compile. Can you suggest why? ? Make changes to the line 'x = x + i;' without changing the order, to make the method compile. ? The value output is '-7616'. Explain why it is negative. Also, explain how Java sets an integer to negative or positive.
Java code
public void outputValue(){short x = 0;int i = 123456;x = x + i;System.out.println(x);}
[解决办法] byte short char int 之间无论那两个做四则运算,结果都是int [解决办法] x + i;这个的返回结果始终是int的,但是你的x却是short,当然会错 [解决办法] 报错原因因为大类型往小类型转换要强制转换,出现负值是因为计算之后数据过大,short最大数值为32767,转换的时候截取了部分内容保存,截取的部分里面的最高位这里是符号位为1了,short是有符号的所以转换过来变为负值。这个问题只能升级short类型来解决,要不越界了确实没办法保存正确的数值。至于如何设置Integer为正负,直接声明的时候给赋值上+-int就行了,jdk5开始就支持基本类型的自动装包拆包了。 [解决办法]
[解决办法] 123456(decimal) = 0x1E240;
When you transfer the int type number the short type number
There is no unsigned int type in Java, so the most significant bit
of int is the sign bit.
As you can see from the binary number, it's a negative number; however, the negative
number is stored by radix complement in computer not true code.
Therefore the true code is 1001 1101 1100 0000 (binary) = -7616 (decimal). [解决办法] 报错原因因为大类型往小类型转换要强制转换,出现负值是因为计算之后数据过大,short最大数值为32767,转换的时候截取了部分内容保存,截取的部分里面的最高位这里是符号位为1了,short是有符号的所以转换过来变为负值。 这个问题只能把short类型换掉,换成int类型或比int类型大的。。。。如long [解决办法] public void outputValue(){ short x = 0; int i = 123456; x = x + i; System.out.println(x); }
转型错误 java是向上转型的的short能转换为int,但是int转换为short会报错的 int i x + i; 类型会被转成int 但是你把int转换为short则必定错了 可以写成 x = (short)(x + i);