Question:
Integer.parseInt(Integer) Java?
AT
2009-10-03 21:02:22 UTC
expected ... sumNumbers("aa11b33") → 44
error ... Exception:java.lang.NumberFormatException: For input string: "" (line number:11)


public int sumNumbers(String str) {
int length=str.length();
int num=0;
String string="";

for(int i=1; i if(Character.isDigit(str.charAt(i))){
string=string+str.charAt(i);
}
else if(!Character.isDigit(str.charAt(i))){
num=Integer.parseInt(string);
string="";
}

}

return num;
}
Three answers:
anonymous
2009-10-03 21:15:15 UTC
If this line executes it will always throw an exception: num=Integer.parseInt(string);

You probably want it outside of your for loop.

FYI if(!Character.isDigit(str.charAt(i))) will always be true if you are already in your else clause.
Mark aka jack573
2009-10-07 11:17:34 UTC
Change your code to this:



public int sumNumbers(String str) {

int length=str.length();

int num=0;

String string="";



for(int i=1; i
if(Character.isDigit(str.charAt(i))){

string=string+str.charAt(i);

}

// else if(!Character.isDigit(str.charAt(i))){

// num=Integer.parseInt(string);

// string="";

// }



}

if ( ! string.equals( "" ))

{

num = Integer.parseInt( string );

}



return num;

}
Dyann
2016-04-06 01:33:13 UTC
Not sure what is going on in this thread, though I for one agree with Angel on this one. If you practice common sense, and have an up to date version of java with up to date security software., then you should be ok. I laugh sometimes when people are so worried about java and telling people to completely remove all traces of it (though you can IF you have no need for it, though many apps REQUIRE java to run at all), while running an unpatched (with many non-installed) version of say Windows Vista. MS itself (I am completely guessing... I do not have stats to back this up, I admit it) seems to have just as many security issues as java itself, but some seem to "freakout" over java issues (I do recommend updating any PC you have that does have java on it) also, if your in a corporate environment, I could understand completely disabling java, though since so many apps and web apps need it, mass uninstalling it wouldn't (just my opinion) be advisable until you know you will not end up removing it on a ton of computers, to find out, it is needed for some reason, THEN have to reinstall it back all over again. Testing it, by disabling it (say in Firefox Plugins) in your browser but not totally removing it, is a good idea , if you want to test, if sites need it. You can simply re-enabling it if you need to later -Xmetalfanx


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...