user7951292
user7951292

Reputation:

Android - Out of bounds on a simple array

tubeDataSplit has multiple lines with 4 numbers seperated by ; each row. tubeDataSpliter should split this 4 numbers and use it on TubeData.

My problem is that when tubeDataSplit is bigger than 4 the program crashes because tubeDataSpliter array is out of bounds. So I assume tubeDataSpliter is the size of the ; spacings.

How can I avoid this?

    String[] tubeDataSplit = tubeDataString.split("\\n");
    String[] tubeDataSpliter;

    for(int i=0; i<tubeDataSplit.length -1;i++) {


        tubeDataSpliter = tubeDataSplit[i].split(";");


        if (tubeDataSpliter[i] != null) {
            TubeData newTubeData = new TubeData(tubeDataSpliter[0], Float.parseFloat(tubeDataSpliter[1]), Float.parseFloat(tubeDataSpliter[2]), Float.parseFloat(tubeDataSpliter[3]));
            tubeDataArrayList.add(newTubeData);

        }

    }

Upvotes: 0

Views: 54

Answers (3)

Ivo
Ivo

Reputation: 23164

if (tubeDataSpliter[i] != null) { is wrong.

When you have more than 4 lines than i becomes 4 or larger and tubeDataSpliter[4] is beyond the bounds of the array since it's length 4.

what you should do instead at that line is:

if (tubeDataSpliter.length == 4) {

Upvotes: 0

Mohammad nabil
Mohammad nabil

Reputation: 1020

for(int i=0; i<tubeDataSplit .length(); i++){

    TubeData newTubeData = new TubeData();
    newTubeData.setTubeData(tubeDataSpliter[i]);
    tubeDataArrayList.add(newTubeData);
}

//In TubeData.class add string and generate getter and setter

private Strind tubeDate;

Upvotes: 0

Vikas Tiwari
Vikas Tiwari

Reputation: 499

Modify your if condition with below code:

 if (tubeDataSplitter != null && tubeDataSpliter.length >=4 ) {
            TubeData newTubeData = new TubeData(tubeDataSpliter[0], Float.parseFloat(tubeDataSpliter[1]), Float.parseFloat(tubeDataSpliter[2]), Float.parseFloat(tubeDataSpliter[3]));
            tubeDataArrayList.add(newTubeData);

        }

Upvotes: 1

Related Questions