如果用户键入"C",我只想输出为12.0,输入"H"就相同.问题是输入存储为字符串正确吗?我试图通过Double.parseDouble将字符串转换为double
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
}
}
Run Code Online (Sandbox Code Playgroud)
您不希望将值存储为字段,而是将它们存储在地图中:
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...
}
Run Code Online (Sandbox Code Playgroud)
然后,在output()中:
return values.get(input.nextLine());
Run Code Online (Sandbox Code Playgroud)
使用常量字段进行此操作的唯一方法是使用反射,并且您真的不想去那里.
归档时间: |
|
查看次数: |
334 次 |
最近记录: |