Model to avoid out of bounds exception in Java

838 Views Asked by At

I am reading data from a file, one line at a time. The number of elements in the line can vary. I am using Java 8.

public boolean display (Integer code, String line) {

    String[] strArray = line.split(Constant.sep);

    String name     = strArray[0];
    String address  = strArray[1];
    String country  = strArray[2];

    //Do Something Scenario (if only name is Not Null, OR if name & address are not null or ....
}

In the above case, not all the fields are necessary for the follow up execution.

However, strArray goes out of bound in the above case, say, when e.g. only field "name" is present. I understand, why this happens. Is there a solution to get around this?

I would prefer to simplify the code and not have to create separate code for each situation or build a complex If/else logic for each combination. The value "code" is a helper that tells the method that what fields are present in the "String line".

2

There are 2 best solutions below

0
On

Use if statements.

String name = “default”;
String address = “default”;
String country = “default”;
int length = strArray.length;
if(length > 1)
    name = strArray[0];
if(length > 2)
    address = strArray[1];
if(length > 3)
    country = strArray[2];

This works because the code “falls through” to each if statement. If the length is 2, then the third if statement is not executed but the first two are. This allows for you to avoid repeating yourself and using a long if statement structure.

0
On

As long as you are using java8, I guess this would be useful, this is a simple try with Optional:

public boolean display(Integer code, String line) {

    String[] strArray = line.split(Constant.sep);
    String[] strArrayTemp = new String[3];
    System.arraycopy(strArray, 0, strArrayTemp, 0, strArray.length);

    String name = "";// or anything that represents your default value
    String address = "";
    String country = "";

    if (Optional.ofNullable(strArrayTemp[0]).isPresent())
        name = strArrayTemp[0];

    if (Optional.ofNullable(strArrayTemp[1]).isPresent())
        address = strArrayTemp[1];

    if (Optional.ofNullable(strArrayTemp[2]).isPresent())
        country = strArrayTemp[2];

    //complete your logic ...

    return true; // I guess
}