gpt4 book ai didi

java - java 对象上的不兼容类型

转载 作者:行者123 更新时间:2023-12-01 19:34:59 26 4
gpt4 key购买 nike

编译器不喜欢将对象中的元素分配给变量类型 Double,即使元素类型是 Double。我错过了什么?

Object relWeights [][] = new Object[2][];
relWeights[0] = new String [] {
"Venus", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"
};
relWeights[1] = new Double [] {
0.78, 0.39, 2.65, 1.17, 1.05, 1.23
};
Double temp = relWeights[1][planetVisiting-1];
//compiler faults here with incompatible types

System.out.println("Your weight on " + relWeights[0][planetVisiting-1] + " is " + temp*weightOnEarth +"pounds");
}

最佳答案

@SSP 建议的解决方案很好地描述了该问题:编译器只知道您的条目具有 Object 类型。需要进行类型转换来告诉编译器它是一个double

对于推断的用例,我建议使用 Map 而不是数组。不过,基本解决方案会有点不同。

Map<String, Double> relWeights = new HashMap();
relWeights.put("Venus", 0.78);
relWeights.put("Mars", 0.39);
relWeights.put("Jupiter", 2.65);
relWeights.put("Saturn", 1.17);
relWeights.put("Uranus", 1.05);
relWeights.put("Neptune", 1.23);

Map 是一个键值存储。它为每个键分配一个值。可以使用 relWeights.get("specic_key") 来获取分配给该键的值(在此示例中,Double 分配给 String).

String planet = "Jupiter";
double temp = relWeights.get(planet);
double weightOnEarth = 38.62;

System.out.println("Your weight on " + selectedPlanet + " is "
+ temp*weightOnEarth + "pounds");

但是,如果您需要按数字输入条目,请务必注意 HashMap 不是有序的。在这种情况下,您应该使用 LinkedHashMap,并且当您需要按位置检索时,将值转换为 ArrayList

LinkedHashMap<String, Double> relWeights = new LinkedHashMap<>();
relWeights.put("Venus", 0.78);
relWeights.put("Mars", 0.39);
relWeights.put("Jupiter", 2.65);
relWeights.put("Saturn", 1.17);
relWeights.put("Uranus", 1.05);
relWeights.put("Neptune", 1.23);

Double temp = (new ArrayList<Double>(relWeights.values())).get(position);

关于java - java 对象上的不兼容类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58177999/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com