有没有一种方法可以选择一个数组而不指定它

时间:2019-05-28 17:49:41

标签: java android

我想从数组中获取一个数字,而不必执行很多if语句。

double[] PVC_A1_Cu = new double[]{14.5d, 19.5d, 26.0d, 34.0d, 46.0d, 61.0d, 80.0d, 99.0d, 119.0d, 151.0d, 182.0d, 210.0d, 240.0d, 273.0d, 321.0d, 367.0d};
double[] PVC_A2_Cu = new double[]{14.0d, 18.5d, 25.0d, 32.0d, 43.0d, 57.0d, 75.0d, 92.0d, 110.0d, 139.0d, 167.0d, 192.0d, 219.0d, 148.0d, 291.0d, 334.0d};
double[] PVC_B1_Cu = new double[]{17.5d, 24.0d, 32.0d, 41.0d, 57.0d, 76.0d, 101.0d, 125.0d, 151.0d, 192.0d, 232.0d, 269.0d, 300.0d, 341.0d, 400.0d, 458.0d};
double[] PVC_B2_Cu = new double[]{16.5d, 23.0d, 30.0d, 38.0d, 52.0d, 69.0d, 90.0d, 111.0d, 133.0d, 168.0d, 201.0d, 232.0d, 258.0d, 294.0d, 344.0d, 394.0d};

String Kappe = SpinLederKapp.getSelectedItem().toString();   // This would return "PVC"
String LederMat = SpinLederMat.getSelectedItem().toString(); // This would return "A1"
String InsMet = SpinInsMet.getSelectedItem().toString();     //This would return  "Cu"

Integer Tverrsnitt = SpinTverrsnitt.getSelectedItemPosition();  //This would return in this case   "2"

String Codetest = Kappe + "_" + InsMet + "_"+LederMat;  //this would put it together like "PVC_A1_Cu"

Double Test3 = Codetest[Tverrsnitt];  //And here is were my knowledge ends...
//This does not work ^

//What i want it to do:
Double Test1 = PVC_A1_Cu[2];

2 个答案:

答案 0 :(得分:0)

将数组放入Map中(大概一次,然后将其保留在类级别):

Map<String, double[]> map = new HashMap<>();
map.put("PVC_A1_Cu", new double[]{14.5d, 19.5d, 26.0d, 34.0d, 46.0d, 61.0d, 80.0d, 99.0d, 119.0d, 151.0d, 182.0d, 210.0d, 240.0d, 273.0d, 321.0d, 367.0d});
map.put("PVC_A2_Cu", new double[]{14.0d, 18.5d, 25.0d, 32.0d, 43.0d, 57.0d, 75.0d, 92.0d, 110.0d, 139.0d, 167.0d, 192.0d, 219.0d, 148.0d, 291.0d, 334.0d});
map.put("PVC_B1_Cu", new double[]{17.5d, 24.0d, 32.0d, 41.0d, 57.0d, 76.0d, 101.0d, 125.0d, 151.0d, 192.0d, 232.0d, 269.0d, 300.0d, 341.0d, 400.0d, 458.0d});
map.put("PVC_B2_Cu", new double[]{16.5d, 23.0d, 30.0d, 38.0d, 52.0d, 69.0d, 90.0d, 111.0d, 133.0d, 168.0d, 201.0d, 232.0d, 258.0d, 294.0d, 344.0d, 394.0d});

,然后将其与您的Codetest字符串一起使用:

double Test3 = map.get(Codetest)[Tverrsnitt];

请注意,我使用double而不是Double,因为数组是原始双精度数,而不是Double实例。

答案 1 :(得分:0)

这将帮助您了解这里出了什么问题。

首先,您要创建一个双精度数组,

double[] PVC_A1_Cu = ..... //This means create a variable of type double array whose name is PVC_A1_Cu.

稍后您将创建一个字符串变量,

String Codetest = ... //This means create a variable of type String whose name is codetest

最后,您要为字符串变量Codetest分配一个值“ PVC_A1_Cu”(恰好是您的双数组变量名称)。这绝不是意味着您要引用double数组的内容,而只是意味着您的字符串变量的内容为“ PVC_A1_Cu”并且不能像数组一样被引用。因此,当您的代码执行此操作时,编译器会抱怨

Codetest[Tverrsnitt]; //codeTest is not an array

最简单的处理方法是

if("PVC_A1_Cu".equals(Codetest)) {
    test3 = PVC_A1_Cu[Tverrsnitt];
} else ("PVC_A2_Cu".equals(Codetest)) {
    test3 = PVC_A2_Cu[Tverrsnitt];
} else ("PVC_B1_Cu".equals(Codetest)) {
    test3 = PVC_B1_Cu[Tverrsnitt];
} else {
    test3 = PVC_B2_Cu[Tverrsnitt];
}