CharSequence的为Integer多+ ve和-ve signss [英] CharSequence to Integer with multiple +ve and -ve signss
问题描述
我已经了解到,转换的CharSequence为整数,我们可以使用下面的语句
i have learned that to convert charsequence to integer we can use this statement
String cs="123";
int number = Integer.parseInt(cs.toString());
如果
cs = "++-+--25";
将这一声明仍然可以运行,给的答案-25根据给定的字符串??
will this statement still run and give answer -25 according to string given??
推荐答案
您是结了一个 NumberFormatException异常
,因为 ++ - + - 25
不是有效的整数。
You are end up with a NumberFormatException
since ++-+--25
is not a valid integer.
查看<一个href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt%28java.lang.String%29\"相对=nofollow> parseInt函数的文档()
将字符串参数作为有符号的十进制整数。 字符串中的字符必须都是十进制数字,除非第一个字符是ASCII字符的减号' - '('\\ u002D')为指示负值或ASCII加号'+'('\\ u002B')来表示正值。将得到的整数值返回,就好像该参数和基数10作为参数传递给parseInt函数(java.lang.String中,int)方法。
Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method.
所以,你可以做
CharSequence cs = "-25"; //gives you -25
和
CharSequence cs = "+25"; //gives you 25
否则,采取必要的措施来面对例外
:)
所以知道字符序列是一个有效的字符串只写一个简单的方法来返回true或false,然后再继续。
So know the char Sequence is a valid string just write a simple method to return true or false and then proceed further
public static boolean {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false; // no boss you entered a wrong format
}
return true; //valid integer
}
那么你的code看起来像
Then your code looks like
if(isInteger(cs.toString())){
int number = Integer.parseInt(cs.toString());
// proceed remaining
}else{
// No, Operation cannot be completed.Give proper input.
}
这篇关于CharSequence的为Integer多+ ve和-ve signss的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!