Reputation: 1819
I have a data file containing a combination of doubles and strings like this:
Rmax=2.3
Rmin=1.0
etc.
I'm using split() to cut out the = like this:
while ((strLine = br.readLine()) != null) {
String phrase = strLine;
try {
//splits to variable name, value
String[] parsed = phrase.split("[=]");
int parsed[0].toString() = parsed[1];
} catch (PatternSyntaxException e) {
System.out.println("Error: " + e.getMessage());
}
}
Now i'm trying to get the values initialized so that parsed[0] becomes the name of the integer and parsed[1] becomes the value. equivalent to the initializer int name = value;
obviously the line
int parsed[0].toString() = parsed[1];
doesn't work. how do i go about doing this?
Upvotes: 1
Views: 2661
Reputation: 533442
How about this
Map<String, Double> map = new HashMap<String,Double>()
while ((strLine = br.readLine()) != null) {
//splits to variable name, value
String[] parsed = phrase.split("=");
String name = parsed[0];
double value = Double.parseDouble(parsed[1]);
map.put(name, value);
}
As has been mentioned you have to catch NumberFormatException and handle a missing '=' depending on whether these are possible.
If you know all possible fields you could use an enum for the field name.
Instead of using a Map you could use an Object which you set via reflection.
class Config {
double Rmax;
double Rmin;
// add more fields here.
}
Config config = new Config;
while ((strLine = br.readLine()) != null) {
//splits to variable name, value
String[] parsed = phrase.split("=");
try {
String name = parsed[0];
double value = Double.parseDouble(parsed[1]);
Config.class.getField(name).setDouble(value);
} catch (Exception e) {
// log exception.
}
}
Upvotes: 3
Reputation: 298818
You can read it to a Properties
object and do the conversion from there:
Properties props = new Properties();
props.load( /* your file as InputStream */ );
Map<String, Double> parsed = new HashMap<String, Double>();
for(Map.Entry<Object, Object> entry : props.entrySet()){
parsed.put(entry.getKey().toString(),
Double.valueOf(entry.getValue().toString());
}
Upvotes: 2
Reputation: 2276
Maybe you want something like this:
String theName = parsed[0];
double theValue = Double.parseDouble(parsed[1]);
Upvotes: 1