【发布时间】:2014-09-06 02:00:13
【问题描述】:
有谁知道如何修复这个 ClassCastException 错误?我得到: “线程“主”java.lang.ClassCastException 中的异常:java.util.HashMap$Entry 无法转换为 java.lang.Integer?
我的问题是我认为我在那个位置调用整数,但显然不是?此作业将在 2 小时内完成,因此我们将不胜感激。评论应该说明发生了什么。
public class WhyHellothere {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
process(s);
}
public static void process(Scanner s) {
HashMap hashmapofpricing = new HashMap();
HashMap hashmapofcount = new HashMap();
for (int i = 0; i < 1; i = 0) {
String itemDescription;
int count;
double unitPrice;
if ((itemDescription = s.next()).equals("end")) {
break;
}
count = s.nextInt();
Integer quantityValue;
if (hashmapofcount.get(itemDescription) != null) {
quantityValue = (Integer) hashmapofcount.get(itemDescription);
} else {
quantityValue = new Integer(0);
}
hashmapofcount.put(itemDescription, new Integer(new Integer(count).intValue()
+ quantityValue.intValue()));
unitPrice = s.nextDouble() * count;
Double costValue;
if (hashmapofpricing.get(itemDescription) != null) {
costValue = (Double) hashmapofpricing.get(itemDescription);
} else {
costValue = new Double(0);
}
hashmapofpricing.put(itemDescription, new Double(new Double(unitPrice).doubleValue()
+ costValue.doubleValue()));
}
Object itemdescription[] = hashmapofcount.entrySet().toArray();
Object howmanytimestheitemappears[] = hashmapofcount.entrySet().toArray();
int countIteration=0;
Object pricing[] = hashmapofpricing.entrySet().toArray();
int priceIteration=0;
Integer runningmaxamount = new Integer(0);
for (int i = 0; i < howmanytimestheitemappears.length; i++) {
int q = (Integer)howmanytimestheitemappears[i];//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<this is where the ClassCastException is. No idea why or how to fix.
if (q > runningmaxamount.intValue()) {runningmaxamount = q;countIteration = i;
}
}
Double maxcost = new Double(0);
for (int i = 0; i < pricing.length; i++) {
Double d = (Double) pricing[i];
if (d.doubleValue() > maxcost.doubleValue()) {
maxcost = d;
priceIteration = i;
}
}
String largestCountItem = (String) itemdescription[countIteration];
String largestCostItem = (String) itemdescription[priceIteration];
System.out.println("The largest count item with "
+ runningmaxamount.intValue() + " was: " + largestCountItem);
System.out.println("The largest total cost item at "
+ maxcost.doubleValue() + " was: " + largestCostItem);
}
}
【问题讨论】:
-
请帮我们一个忙,从您的代码中删除所有分散注意力的 cmets。我们越容易阅读和理解您的代码,就越容易为您提供帮助。此外,请务必通过明显的注释(可能是代码中应该存在的 only 注释)指出哪一行会导致您的问题。
-
你的 cmets 让你的代码不可读...
-
好吧,如果您查看文档,HashMap$Entry 和 Integer 之间唯一的共同父对象是 Object。
-
我已经删除了所有凌乱的 cmets,只有例外的行有任何 cmets。底部附近的一系列
-
好的,我明白了。并且 howmanytimestheitemapears 数组填充了
hashmapofcount.entrySet().toArray(),所以如果它不包含 HashMap 条目会很奇怪。你期待什么?