Q: Generate Variables from array to create loop So I have this array which I am generating when reading and splitting variables from a text file. I then Need to parse split variable in the array into an integer and surround it in a try catch in case the data is not an integer. I am trying to avoid creating a try catch block for each variable in the array. This is my code so far:
String [] tempList = data.split("-");

String [] variables = {"readerNo", "seconds", "minutes", "hours", 
                       "days", "month", "year", "other","empNo"};
int readerNo, seconds, minutes, hours, days, month, year,other, empNo;
/*
* parsing of data to integers/boolean
*/

//-----------
for(int i = 0; i < variables.length; i++) {
    try{
        *variable name should be here* = Integer.parseInt(tempList[i]); 
    }catch(Exception E){
        *variable name should be here* = -1; 
    }
}

Would it be possible or would I need to create a try catch block for each?

A: Try to do it like that:
int[] myNumbers = new int[tempList.length];
for(int i = 0; i < tempList.length; i++){
  try{
     myNumbers[i] = Integer.parseInt(tempList[i]); 
  }catch(Exception E){
     myNumbers[i] = -1; 
  }
}

Thats the method to avoid the try{}- Blocks :)

A: I think a nice way is to use a regex:
if(tempList[i].matches("-?\\d+"))
{
  Integer.parseInt(tempList[i]); 
}

There are several ways to check if a string represents an integer. If you want to dodge that exception you will need to know it is an int before attempting a parse. See here for related: Determine if a String is an Integer in Java
