日期:2014-05-20  浏览次数:20725 次

这个程序为什不能编译?怎样修改,怎样设置负值?
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开始就支持基本类型的自动装包拆包了。
------解决方案--------------------
探讨
报错原因因为大类型往小类型转换要强制转换,出现负值是因为计算之后数据过大,short最大数值为32767,转换的时候截取了部分内容保存,截取的部分里面的最高位这里是符号位为1了,short是有符号的所以转换过来变为负值。这个问题只能升级short类型来解决,要不越界了确实没办法保存正确的数值。至于如何设置Integer为正负,直接声明的时候给赋值上+-int就行了,jdk5开始就支持基本类型的自动……

------解决方案--------------------
123456(decimal) = 0x1E240;

When you transfer the int type number the short type number

the redundant numbers will be discarded.

0x1E240 becomes 0xE240 = 1110 0010 0100 0000 (binary);

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);


------解决方案--------------------
首先定义了x的类型是short的,但是Java的底层计算是用int计算的,所以x+1的计算结果是int类型的,然后是int类型转换到short类型,大类型到小类型转换需要强制类型转换,所以x+1改成(short)x+1即可;
------解决方案--------------------
x是short类型,而x+i结果会自动转换成int类型,int类型转换成short类型需要写成x=(short)(x+i)进行强制转换。