0

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?

3
  • Check this question/answer: stackoverflow.com/questions/6729605/… Commented Jul 24, 2014 at 9:17
  • It is bad practice to catch Exception, catch NumberFormatException instead. Commented Jul 24, 2014 at 9:19
  • You are right @Raphaël. Bad habit. Commented Jul 24, 2014 at 9:23

2 Answers 2

2

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 :)

Sign up to request clarification or add additional context in comments.

3 Comments

He wrote that he wants to avoid writing try-catch for every single variable :)
it is different because he, for every single variable, uses an own integer. I just use a integer[]
I think that he wants to have it answered like I did because he has like 8 integers.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.