我正在使用Android Eclipse Indigo Release 2,而且我遇到了parseInt()函数的问题。我有一个字符串缓冲区,我解析得到一个Integer值。问题是它只能使用2位整数才能正常工作,但不能使用单个数字。我进一步尝试使用" radix"条款纠正问题,但没有运气。如果我使用基数对字符串进行硬编码,则可以正常工作:
case PIN_STATE:
int pin_state = 0;
String statebuff = (String) msg.obj;
if (msg.arg1 > 0) {
try{
pin_state=Integer.parseInt(statebuff,10); //Doesn't work for single-digit integers
pin_state=Integer.parseInt("01",10); // equals = 1 hard code works below correctly
} catch(NumberFormatException nfe) {
return;
}
switch (pin_state){
case 1: //RESYNC_THERMO_ON: //Sync module state - thermostat is on
ThermoCheck.setChecked(true);
ThermoTxt.setText(R.string.ThermoOn);
ThermoTxt.setTextColor(Color.BLUE);
ThermoTxt.setVisibility(View.VISIBLE);
fanSpeedTxt.setVisibility(View.INVISIBLE);
break;
case 12: //work great without any modifications to the parseInt() function above
ThermoCheck.setChecked(true);
ThermoTxt.setText(R.string.ThermoOn);
ThermoTxt.setTextColor(Color.BLUE);
ThermoTxt.setVisibility(View.VISIBLE);
fanSpeedTxt.setVisibility(View.INVISIBLE);
break;
default: //Do something
}
}
答案 0 :(得分:1)
您的断言是错误的,
String statebuff = "1";
int v = Integer.parseInt(statebuff,10);
System.out.println(v);
打印1.您的statebuff
值不是您想象的,我的假设是它有空格。
int v = Integer.parseInt(statebuff.trim()); // <-- add a trim call, also parseInt is
// decimal by default so 10 is
// redundant.