CharSequence to Integer with multiple +ve and -ve signss

ⅰ亾dé卋堺 提交于 2020-01-06 03:24:13

问题


i have learned that to convert charsequence to integer we can use this statement

String cs="123";    
int number = Integer.parseInt(cs.toString());

what if

cs = "++-+--25";

will this statement still run and give answer -25 according to string given??


回答1:


You are end up with a NumberFormatException since ++-+--25 is not a valid integer.

See the docs of parseInt()

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.

So you are allowed to do

CharSequence cs = "-25"; //gives you -25

and

CharSequence cs = "+25";   //gives you 25

Otherwise ,take necessary steps to face the Exception :)

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
}

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.
}



回答2:


Answer to your question is code will run and throw Exception as "++-+--25" is not a valid int,

   java.lang.NumberFormatException: For input string: "++-+--25"



回答3:


You will get

java.lang.NumberFormatException: For input string: "++-+--25"

Tested example :

CharSequence cs = "++-+--25";
System.out.println("" + Integer.parseInt(cs.toString()));


来源:https://stackoverflow.com/questions/19488067/charsequence-to-integer-with-multiple-ve-and-ve-signss

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!