【发布时间】:2015-12-13 20:55:21
【问题描述】:
我正在尝试完成一项练习,其中有一些任务,包括以下任务: 仅打印数组中 3 的倍数 我必须使用小程序,但我不知道该怎么做。 我试图在图形部分设置一个条件,但它返回一个不好的 0
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);
}
}
}
在我尝试基于 3 的倍数的值的数量的计算创建一个新数组的另一次尝试中,程序没有启动,我得到 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 < dataList.length; i++)和for (int i = 0; i < multiple3.length; i++)由于数组的第一个索引为零,您实际上想要遍历array.length - 1。 -
没有。这不是问题。它将在检查 小于 - 不是 小于或等于 时进行迭代
-
编译器在这里喷火:multiple3[i] = dataList[i];我按照 Thisaru Guruge 的建议尝试了,但没有成功。
-
正如我在回答中提到的,您必须使用两个不同的计数器。
multiple3[i] = dataList[i];将不起作用。multiple3[j] = dataList[i];会做 -
编译成功,但不显示3的倍数的输入,执行时抛出异常错误。
标签: java arrays algorithm indexoutofboundsexception