How to handle an empty string?

1

I need to convert a string that I get from a text file and populate a person class where, each attribute of the class is separated by "," in the text file. The attributes are only: height, weight, age. In the text file they are as follows:

1.50,58,20

1.60,60,15

And there goes ... The problem is that some of these attributes are not populated and I'm having problems when the last attribute is not filled.

Ex:1.50,58,20

   1.60,60,

   1.70.80.30

In line 2 the last one was not filled and I need to handle this. My code looks like this:

for(String s : result){
            String pessoa[];
            pessoa = s.split(",");
            System.out.println(pessoa[2]);
The result holds in each position a line of the file and I use the variable String pessoa[] to save the separated parts by "," the problem is that when it is pessoa[2] it gives the error java.lang.ArrayIndexOutOfBoundsException: 2 because as the last position was not filled, there really is no index.

How to handle this error? I have tried to create the variable and initialize the indexes as null or "" (vazio) but did not work.

    
asked by anonymous 03.09.2016 / 22:49

2 answers

3

You can solve your problem as follows by simply adding a parameter delimiting the maximum amount of results of the split method, thus s.split(",", 3) .

for(String s : result){

    String pessoa[];
    pessoa = s.split(",", 3);
    System.out.println(pessoa[2]);

}

In this way, when trying to access the number 2 index of the person array, an empty string will be returned and not an error as in your code.

Example: use sample.

    
04.09.2016 / 00:12
2

If you do not know if the index really exists, check the size of the array before accessing it. So we use repetition loops, because they control the flow so that we do not try to access a non-existent position.

You can check before displaying whether that vector is size 3 or greater:

for(String s : result){
    String pessoa[];
    pessoa = s.split(",");
    System.out.println(pessoa.length >= 3 ? pessoa[2] : "");
}

Where I put "" you can change it so that it is displayed if index 2 does not exist.

See working in IDEONE

    
03.09.2016 / 23:31