I’ve got a text file with data for my application and I want to create objects with that data. Every line in the text file is one object in format: <name> <posX> <posY> <posY> <velX> <velY> <velZ> <mass> <radius>.
line is a String with one line from that file. To read the data I split the string on whitespace. Then I get the first element to the variable name.
String[] args = line.split("\\s+");
String name = args[0];
Then I want to take next parameters from the line. I could surely do it like this:
double posX = Double.parseDouble(args[1]);
double posY = Double.parseDouble(args[2]);
double posZ = Double.parseDouble(args[3]);
double velX = Double.parseDouble(args[4]);
double velY = Double.parseDouble(args[5]);
double velZ = Double.parseDouble(args[6]);
double mass = Double.parseDouble(args[7]);
double radius = Double.parseDouble(args[8]);
However, it doesn’t look great. I have thought about doing it like that:
Map<String, Double> params = new HashMap<>();
String[] keys = {"posX", "posY", "posZ", "velX", "velY", "velZ", "mass", "radius"};
int i = 1;
for (String key : keys) {
params.put(key, Double.parseDouble(args[i]));
i++;
}
Now I’m not sure if it’s the best possible approach to my problem. Do you know any better way to do it?
MyClass mine = new MyClass(myString)will do all the parsing for you.