1
I need to convert a string taken from a text file and fill in a person class where, each attribute of the class is separated by "," in the text file. Attributes are only: height, weight, age. In the text file they are as follows:
1.50,58,20
1.60,60,15
and so on and so forth... The problem is that some of these attributes are not filled and I am 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 treat it. My code is as follows:
for(String s : result){
String pessoa[];
pessoa = s.split(",");
System.out.println(pessoa[2]);
The result
guard, at each position, one line of the file and I use the variable String pessoa[]
to keep the parts separated by "," the problem is that when it is pessoa[2]
makes the mistake java.lang.ArrayIndexOutOfBoundsException: 2
because the last position was not filled, there is not really the index.
How to handle this error? I have tried creating the variable and initializing the indexes as null
or "" (vazio)
but it didn’t work out.
Check the size of the array before using
pessoa[2]
– ramaral
Delimite the amount of Strings to be returned in the split method to 3, thus: s.split(",", 3).
– Yure Pereira