Reputation: 11
If the user types "C" I simply want the output to be 12.0 same goes for typing "H". The problem is that the input is being stored as string correct? I've tried to convert the string to double though Double.parseDouble
import java.util.Scanner;
public class Elements {
Scanner input=new Scanner(System.in);
public static final double H = 1.0;
public static final double Li = 6.9;
public static final double Be = 9;
public static final double B = 10.8;
public static final double C = 12.0;
public double output() {
return C ; // I want the user to choose the variable to return
}
}
Upvotes: 1
Views: 574
Reputation: 1488
Have you thought about using a Switch/case statement using the input?
Upvotes: 0
Reputation: 1218
A map will solve your problem. A map return a value for a specific key.
java.util.HashMap<String, Double> map = new java.util.HashMap<String, Double>();
map.put("C", 12.0);
map.put("H", 1.0);
map.put("B", 10.8);
You can get the value for the input of the user:
Double value = map.get(inputString);
Upvotes: 0
Reputation: 3753
Rather than storing the values as fields, you'll want to store them in a map:
private static final Map<String, Double> values = new HashMap<String, Double>();
static {
values.put("H", 1.0);
values.put("Li", 6.9);
// and so on...
}
Then, in output():
return values.get(input.nextLine());
The only way of doing it with the constant fields as you currently have involves reflection, and you really don't want to go there.
Upvotes: 5