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.