java char转int,javaint转string
我怎么能把String转换为intJava?
我的字符串只包含数字。 我想返回那个表示的数字。
例如,指定字符串' 1234 '的结果应该是数字1234。
StringmyString='1234 ';
int foo=integer.parseint (mystring );
有关详细信息,请参阅Java文档。
例如,这里有两种方法。
integerx=integer.valueof(str;
//or
inty=integer.parseint(str;
这些方法略有不同。
valueOf返回新的或缓存的实例java.lang.Integer
parseInt返回原始int。
所有情况都是如此。 Short.valueOf/parseShort、Long.valueOf/parseLong等。
现在,需要考虑的一个非常重要的问题是,Integer分析器抛出了Javadoc中提到的NumberFormatException异常。
intfoo;
stringstringthatcouldbeanumberornot=' 26263 hello '; //will throw exception
stringstringthatcouldbeanumberornot2=' 26263 '; //will not throw exception
try { foo=integer.parseint (stringthatcouldbeanumberornot );
}catch(numberformatexceptione ) )
//Will Throw exception!
//do something! anything to handle the exception。
}
try { foo=integer.parseint (stringthatcouldbeanumberornot2);
}catch(numberformatexceptione ) )
//No problem this time,butstillitisgoodpracticetocareaboutexceptions。
//Never trust user input : )
//Do something! Anything to handle the exception。
}
要处理此异常,必须从split参数获取整数值或动态分析特定内容。
手动操作:
publicstaticintstrtoint (字符串)。
inti=0;
因特尔=0;
booleanisNeg=false;
//Check for negative sign; if it's there,set the isNeg flag
if(str.Charat(0)=='-' ) {isNeg=true; i=1;
}
//processeachcharacterofthestring;
wile(I
}
if(isneg ) num=-num;
返回编号;
}
我现在正在为大学做作业。 于是,我不能使用像上面的公式那样的几个公式。 通过看ASCII表,总算做好了。 这是一个非常复杂的代码,但可以帮助像我这样受限制的其他人。
首先是接收输入。 在这种情况下是一系列数字。 我给那个String number打电话。 因此,在这种情况下,String number='12 ';
另一个限制是不能使用重复周期。 因此,也不能使用for周期(这将是完美的)。 这限制了我们,但再一次,这是目标。 因为我只需要两位数字,所以简单的charAt解决方法如下。
//obtainingtheintegervaluesofthechar1and2in ascii
intsemilastdigitascii=number.charat (number.length (-2 );
intlastdigitascii=number.charat (number.length (-1 );
如果有代码,只需查看表格并进行必要的调整:
doublesemilastdigit=semilastdigitascii-48; //A quick look,and -48 is the key
doublelastdigit=lastdigitascii-48;
现在为什么要加倍? 那么,因为这是非常“奇怪”的步骤。 现在有两场双打。 1和2,但是需要把那个定为12。 没有任何数学计算可以做。
我们是后者(lastdigit )除以10的方式2/10=0.2 ),所以为什么要加倍)如下。
最后数字=最后数字/10;
这只是个数字。 把最后一个数字转换成小数。 但是现在让我们来看看会发生什么:
doublejointdigits=semilastdigitlastdigit; //1.0 0.2=1.2
不用太深入数学,只需划分单位的数字即可。 你看,我们只考虑0-9,所以除以10的倍数就像做一个保存它的“箱子”。 (请回想一下你的一年级老师什么时候解释你是学分还是一百学分。 所以:
intfinalnumber=(int ) ) jointdigits*10; //Be sure to use parentheses ' (
你去了。 考虑到以下限制,将一系列数字(在本例中为两位数字)转换为两位整数:
另一个解决方案是使用Apache Commons中的NumberUtils。
intnum=numberutils.toint('1234 );
对于字符串无效的数字格式,Apache实用程序非常有用,因为它总是返回0。 所以保存你的try catch块。