You need to sign in to do that
Don't have an account?
Lucy Yuan
How to judge the String can or can't to convert to integer?
Hi
i just meet one question, when i convert the string to integer type. i used the integer.valueof() method . but if string like 'ABCDEF' that can't do integer conversion but throw System.TypeException.
could i do judgement first first? like if the string parameter s='123' can do integer conversion, and then i call the integer.valueof(s)
is there any method ??
Use below utility class containsonly method for validation
Example
All Answers
You may need to adapt the method to your specific needs.
Thanks!
But when the program throw exception, the program will stop here to run catch block . i just to convert a list<String> in one loop. if any exception throwing . it jumping out of loop but stop the program. so i want to do the judement first.
List<String> stringList = new List<String>();
List<Integer> intList = new List<Integer>();
String s1 = '123';
String s2 = 'ABC';
stringList.add(s2);
stringList.add(s1);
try{
Interger i ;
for(String s : stringList){
i = Integer.valueOf(s);
}
}catch(Exception ex){
.....
}
in this scenraio both 2 string will do conversion failure,but what i need is the one of strings that can convert will to convert successfully.
Use below utility class containsonly method for validation
Example
You're right. Instead of
try {
Integer i ;
for (String s : strings) {
i = Integer.valueOf(s);
}
}
catch {
}
Do this:
Integer i ;
for (String s : strings) {
try {
i = Integer.valueOf(s);
}
catch {
i = 0; //or whatever default value you need to assign
}
}