Я пытаюсь выполнить упражнение, в котором у меня есть некоторые задачи, включая этот: Печатать только кратные 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);
}
}
}
в другой попытке, когда я попытался создать новый массив, основанный на вычислении числа значений кратного 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
femmestem
Нет. Это не проблема. Он будет выполнять итерацию, когда он проверяет __lesser than__ - not __lesser или equal__ –
. Компилятор запускает здесь огонь: multiple3 [i] = dataList [i]; Я попробовал, как предложил Этуру Гуруге, не повезло. – JohnSnow