I have a String
array which have both integers as well as strings. I want to calculate the sum of all integer array elements.
class Array{
String container[] = {"Joe","12","Chandler","15","67","Rajat",'a'};
int sum;
for(String element:container){
int num = Integer.parseInt(element);
sum += num;
}
void print(){
System.out.print(sum);
}
}
class ArrayDemo{
public static void main(String args[]){
Array a = new Array();
a.print();
}
}
But the code int num = Integer.parseInt(element)
gives NumberFormatException because Joe
,Chandler
,Rajat
are not integers. So, how to resolve this problem.
The answer should be the sum of 12+15+67=94
Thanks in advance