0

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

user3520629
  • 185
  • 1
  • 3
  • 15

2 Answers2

3

Include your parse inside a try catch block

for(String element:container){
  try {
    int num = Integer.parseInt(element); 
    sum += num;
  catch (NumberFormatException nfe){
    System.out.println ("Element " + element + " in the array is not an integer");
  }
}
SCouto
  • 7,808
  • 5
  • 32
  • 49
-1

you need to handle that exception:

class Array{
String container = {"Joe","12","Chandler","15","67","Rajat",'a'};
int sum;
for(String element:container){
    try {
        int num = Integer.parseInt(element); 
    catch(Exception e) {
        continue;
    }
    sum += num;
}
void print(){
    System.out.print(sum);
}
}
class ArrayDemo{
public static void main(String args[]){
    Array a = new Array();
    a.print();
}
}

Use try-catch for this. If exception happens, just continue to next iteration in for loop. When its a number, it will be added to sum.

Another approach is to check each char in string if its a number. This is a quite long code, so use one existing (you will need to include Apache Commons library):

NumberUtils.isNumber(String str)

or

StringUtils.isNumeric(String str)

When this gives you true, add it to sum.

Adnan Isajbegovic
  • 2,227
  • 17
  • 27