【发布时间】:2019-06-11 22:18:34
【问题描述】:
我创建了一个赋值程序,该程序要求我使用嵌套增强的 for 循环来显示数组的元素。
我收到无法从元素类型 Integer[] 转换为 int 的错误。
myArray 已在构造函数中正确实例化和初始化。我知道这是正确的,因为我可以很好地以列表格式显示数组的元素,从 1 到 60。
public void displayArrayProduct() {
DecimalFormat decimalFormat = new DecimalFormat("#.##");
decimalFormat.setGroupingUsed(true);
decimalFormat.setGroupingSize(3);
int p=1;
System.out.print("The product of all element of myArray is ");
for (int a : myArray) {
for (int b : myArray) {
p = p + myArray[a][b];
}
}
System.out.println(decimalFormat.format(p));
}
}
我期望这样做是输出数组中所有元素的总和。我用常规的 for 循环尝试了完全相同的事情,并且效果很好。不幸的是,当我切换到增强的 for 循环时,它停止了工作,给了我错误:
类型不匹配:无法从元素类型 Integer[] 转换为 int
这是我的构造函数的样子:
ExerciseTwo() {
myArray = new Integer[6][10];
for (int i = 0; i < myArray.length; i++) {
for (int j = 0; j < myArray[i].length; j++) {
this.myArray[i][j] = i + 1;
}
}
}
【问题讨论】:
标签: java arrays for-loop foreach