我想完成一个练习,其中我有一些任务包括这一个: 仅打印数组中的3的倍数 我必须使用小程序,而且我不知道如何去做。 我试图设置上的图形部分的条件,但它在另一种尝试中,我试图基于对图3中,值数倍的数的计算来创建一个新的数组返回一个不是很好0仅打印数组中的3的倍数
public void init() {
dataList = new int[17];
int dataList[] = {2,4,6,9,5,4,5,7,12,15,21,32,45,5,6,7,12};
for (int i = 0; i < dataList.length; i++) {
//Compute the sum of the elements in the array.
sum += dataList[i];
//Compute the product of the elements in the array.
product *= dataList[i];
//Compute the frequency of the number 5 in the array
if (dataList[i] == 5) {
fiveCounter++;
}
}
}
public void paint(Graphics g) {
g.drawString(("Sum of elements is: " + sum), 25, 25);
g.drawString(("Product of elements is: " + product), 25, 50);
g.drawString(("Number 5 is present " + fiveCounter + " times"), 25, 75);
for (int i = 0; i < dataList.length; i++) {
if ((dataList[i] % 3) == 0) {
g.drawString((String.valueOf(dataList[i])), 25, 100);
}
}
}
程序无法启动,我得到ArrayIndexOutOfBoundException
public void init() {
dataList = new int[17];
multiple3 = new int[mult3Counter];
int dataList[] = {2,4,6,9,5,4,5,7,12,15,21,32,45,5,6,7,12};
for (int i = 0; i < dataList.length; i++) {
//Compute the sum of the elements in the array.
sum += dataList[i];
//Compute the product of the elements in the array.
product *= dataList[i];
//Compute the frequency of the number 5 in the array
if (dataList[i] == 5) {
fiveCounter++;
}
if ((dataList[i] % 3) == 0) {
multiple3[i] = dataList[i];
mult3Counter++;
}
}
public void paint(Graphics g) {
g.drawString(("Sum of elements is: " + sum), 25, 25);
g.drawString(("Product of elements is: " + product), 25, 50);
g.drawString(("Number 5 is present " + fiveCounter + " times"), 25, 75);
for (int i = 0; i < multiple3.length; i++) {
g.drawString((String.valueOf(multiple3[i])), 25, 100);
}
}
我该如何解决这个问题?
提示:错误消息'ArrayIndexOutOfBoundException'意味着你试图遍历一个指数超越数组的长度。问题在于: 'for(int i = 0; i
femmestem
不,这不是问题。它会迭代,因为它检查__lesser比___ - 不__lesser或equal__ –
编译器在这里吐出火:multiple3 [i] = dataList [i]; 我试着按照Thisaru Guruge的建议,没有运气。 – JohnSnow