我有下面的代码,这会给出不稳定的结果。
int nibbleToInt(String val) {
int result;
if(val.substring(3,4) == "1") { result += 1; }
if(val.substring(2,3) == "1") { result += 2; }
if(val.substring(1,2) == "1") { result += 4; }
if(val.substring(0,1) == "1") { result += 8; }
return result;
}我用nibbleToInt("0010");调用函数,它返回8663
编辑:
以下是由于以下响应而产生的工作计划:
int nibbleToInt(String val) {
int result = 0;
if(val.substring(3,4) == "1") { result += 1; }
if(val.substring(2,3) == "1") { result += 2; }
if(val.substring(1,2) == "1") { result += 4; }
if(val.substring(0,1) == "1") { result += 8; }
return result;
}发布于 2014-06-02 16:19:55
如果初始化result,可能会看到不同的结果。:)否则(我相信)每次都会占用内存中的现有价值。
https://stackoverflow.com/questions/23998967
复制相似问题