我已经了解到,转换CharSequence的整数,我们可以使用这个语句
String cs="123";
int number = Integer.parseInt(cs.toString());
如果
cs = "++-+--25";
将这一声明仍然可以运行,给出的回答-25根据给定的字符串?
我已经了解到,转换CharSequence的整数,我们可以使用这个语句
String cs="123";
int number = Integer.parseInt(cs.toString());
如果
cs = "++-+--25";
将这一声明仍然可以运行,给出的回答-25根据给定的字符串?
您是结束了一个NumberFormatException
,因为++-+--25
是不是一个有效的整数。
见parseInt函数的文档()
将字符串参数作为有符号的十进制整数。 字符串中的字符必须都是十进制数字,不同的是第一个字符可以是ASCII减号“ - ”(“\ u002D”)为以指示一个负值或ASCII加号“+”(“\ u002B”)指示正值。 将得到的整数值返回,就好像该参数和基数10作为参数传递给parseInt函数(java.lang.String中,int)方法。
所以,你被允许这样做
CharSequence cs = "-25"; //gives you -25
和
CharSequence cs = "+25"; //gives you 25
否则,采取必要措施,面对Exception
:)
所以知道字符序列是一个有效的字符串只写一个简单的方法来返回true或false,然后再继续
public static boolean {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false; // no boss you entered a wrong format
}
return true; //valid integer
}
然后你的代码看起来像
if(isInteger(cs.toString())){
int number = Integer.parseInt(cs.toString());
// proceed remaining
}else{
// No, Operation cannot be completed.Give proper input.
}
回答你的问题是代码将运行并抛出异常为“++ - + - 25”不是有效的int,
java.lang.NumberFormatException: For input string: "++-+--25"
你会得到
java.lang.NumberFormatException: For input string: "++-+--25"
测试的例子:
CharSequence cs = "++-+--25";
System.out.println("" + Integer.parseInt(cs.toString()));