Skip to content Skip to sidebar Skip to footer

Charsequence To Integer With Multiple +ve And -ve Signss

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

Solution 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

CharSequencecs="-25"; //gives you -25

and

CharSequencecs="+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

publicstaticboolean  {
    try { 
        Integer.parseInt(s); 
    } catch(NumberFormatException e) { 
        returnfalse;  // no boss you entered a wrong format
    }

    returntrue; //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.
}

Solution 2:

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

   java.lang.NumberFormatException: For inputstring: "++-+--25"

Solution 3:

You will get

java.lang.NumberFormatException: For inputstring: "++-+--25"

Tested example :

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

Post a Comment for "Charsequence To Integer With Multiple +ve And -ve Signss"