Почему мой код не работает?
Нужно создать массив, заполнить случайными числами от 1 до 10 и найти произведение всех этих чисел.
public static void main(String[] args) {
int[] array = new int[10];
for (int i = 0; i < array.length; i++) {
array[i] = 1 + (int) (Math.random() * 11);
}
long p = array[0] * array[1] * array[2] * array[3] * array[4] * array[5] * array[6] * array[7] * array[8] * array[9];
System.out.println(p);
}
задан 12 июл 2020 в 14:56
2
int p = 0; // !!! Не торопитесь. Подумайте.
...
p = p * array[i];
Вы доводите счетчик внешего цикла i до array.length во внутреннем цикле. Зачем тут вложенные циклы?
public static void main(String[] args) {
int[] array = new int[10];
int p = 1;
for (int i = 0; i < array.length; i++) {
array[i] = (int) (Math.random() * 10);
p = p * array[i];
}
System.out.println(p);
}
ответ дан 12 июл 2020 в 14:59
14
To find the product of elements of an array.
- create an empty variable. (product)
- Initialize it with 1.
- In a loop traverse through each element (or get each element from user) multiply each element to product.
- Print the product.
Example
Live Demo
import java.util.Arrays;
import java.util.Scanner;
public class ProductOfArrayOfElements {
public static void main(String args[]){
System.out.println("Enter the required size of the array :: ");
Scanner s = new Scanner(System.in);
int size = s.nextInt();
int myArray[] = new int [size];
int product = 1;
System.out.println("Enter the elements of the array one by one ");
for(int i=0; i<size; i++){
myArray[i] = s.nextInt();
product = product * myArray[i];
}
System.out.println("Elements of the array are: "+Arrays.toString(myArray));
System.out.println("Sum of the elements of the array ::"+product);
}
}
Output
Enter the required size of the array: 5 Enter the elements of the array one by one 11 65 22 18 47 Elements of the array are: [11, 65, 22, 18, 47] Sum of the elements of the array:13307580
I am stuck and if someone can point me in the right direction would be fantastic. I have this code below and I need to add a method that returns the product of elements in the array.
public class ArrayProduct
{
public static void main( String [] args )
{
int [] intArray = { 1, 2, 3, 4, 5, 6 };
System.out.print( "The elements are " );
for ( int i = 0; i < intArray.length; i++ )
System.out.print( intArray[i] + " " );
System.out.println( );
System.out.println( "The product of all elements in the array is "
+ arrayProduct( intArray ) );
}
// Insert your code here
}
I’m just not sure of a way to solve this without completely changing the code all together!
asked Dec 8, 2014 at 8:58
3
public static int arrayProduct(int[] array){
int rtn=1;
for(int i: array){
rtn*=i;
}
return rtn;
}
answered Dec 8, 2014 at 9:11
Patrick ChanPatrick Chan
1,01910 silver badges14 bronze badges
1
You need a new variable in which to store the result. This variable has to be initialized with the neutral integer for multiplication.
answered Dec 8, 2014 at 9:11
AdrianSAdrianS
1,9507 gold badges33 silver badges51 bronze badges
|
0 / 0 / 0 Регистрация: 05.12.2018 Сообщений: 23 |
|
|
1 |
|
Произведение элементов массива14.12.2018, 12:41. Показов 2511. Ответов 5
Составьте программу вычисления произведения элементов, больших заданного числа Т, одномерного массива А(N), заполнив его случайным образом.(java)
0 |
|
3638 / 2970 / 918 Регистрация: 05.07.2013 Сообщений: 14,220 |
|
|
14.12.2018, 12:52 |
2 |
|
что непонятно?
0 |
|
2442 / 1898 / 475 Регистрация: 17.02.2014 Сообщений: 9,154 |
|
|
14.12.2018, 13:04 |
3 |
|
0 |
|
dmitryhad 1 / 0 / 1 Регистрация: 27.08.2015 Сообщений: 33 |
||||
|
14.12.2018, 13:18 |
4 |
|||
|
Решение
0 |
|
Am I evil? Yes, I am! 16117 / 9003 / 2605 Регистрация: 21.10.2017 Сообщений: 20,705 |
|
|
14.12.2018, 13:26 |
5 |
|
dmitryhad, вполне достаточно одного цикла. Добавлено через 2 минуты
0 |
|
2442 / 1898 / 475 Регистрация: 17.02.2014 Сообщений: 9,154 |
|
|
14.12.2018, 14:46 |
6 |
|
Aviz__? Да, блин, как только поймешь (или думаешь, что понял) принцип стримов, то так лень писать циклы
0 |
Порой обучение продвигается с трудом. Сложная теория, непонятные задания… Хочется бросить. Не сдавайтесь, все сложности можно преодолеть. Рассказываем, как
Не понятна формулировка, нашли опечатку?
Выделите текст, нажмите ctrl + enter и опишите проблему, затем отправьте нам. В течение нескольких дней мы улучшим формулировку или исправим опечатку
Что-то не получается в уроке?
Загляните в раздел «Обсуждение»:
- Изучите вопросы, которые задавали по уроку другие студенты — возможно, ответ на ваш уже есть
- Если вопросы остались, задайте свой. Расскажите, что непонятно или сложно, дайте ссылку на ваше решение. Обратите внимание — команда поддержки не отвечает на вопросы по коду, но поможет разобраться с заданием или выводом тестов
- Мы отвечаем на сообщения в течение 2-3 дней. К «Обсуждениям» могут подключаться и другие студенты. Возможно, получится решить вопрос быстрее!
Подробнее о том, как задавать вопросы по уроку

Сообщение было отмечено Lprog как решение


