gpt4 book ai didi

java - 只打印数组中 3 的倍数

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:58:13 26 4
gpt4 key购买 nike

我正在尝试完成一个练习,其中我有一些任务,包括这个:只打印数组中 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);
}
}

我该如何解决这个问题?

最佳答案

您不能对两个数组使用相同的计数器。使用两个不同的计数器。您不能使用 mult3Counter 作为数组 multiple3 的大小,因为它未初始化!因此,mult3Counter 默认为 0。因此,当您要使用任何索引访问 multiple3[] 时,它会给出 ArayIndexOutOfBoundsException

如果要知道3的倍数出现的次数,就得循环两次;

int mult3Counter = 0;
for (int i = 0; i < dataList.length; i++) {
if ((dataList[i] % 3) == 0) {
mult3Counter++;
}
}

int j = 0;
int [] multiple3 = new int[mult3Counter];

for (i = 0; i < dataList.length; i++)
{
if ((dataList[i] % 3) == 0)
{
multiple3[j++] = dataList[i];
}
}

或者最好的方法是使用List(ArrayList)来添加3的倍数。

ArrayList<int> multiple3 = new ArrayList<>();

for (int i = 0; i < dataList.length; i++) {
if ((dataList[i] % 3) == 0) {
multiple3.add(dataList[i]);
}
}

如果需要数组,后面可以转成数组。引用This Question

关于java - 只打印数组中 3 的倍数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34256228/

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