0

Initialize each of the elements of the array PRODUCT to 1

Hyee I'm not sure how to initialize all the elements to 1 but I did this public class Array{ public static void main (String[]args){ int[]product = new int[10]; for (int i=0; i<product; i++){ Then what should I write then?

28th Jan 2023, 4:56 PM
Aenul
Aenul - avatar
7 Answers
+ 2
for( int i = 0; i < product.length; i++) product[i] = 1;
28th Jan 2023, 5:06 PM
Jayakrishna 🇮🇳
+ 2
You can use a loop. You can use a iterator. You can use Arrays.asList(product) You can use streams as Arrays.stream(product).foreach(System.out::println); But the simplest is Arrays.toString(product);
28th Jan 2023, 7:43 PM
Jayakrishna 🇮🇳
+ 1
There's a fill method that makes it more easier Arrays.fill(product, 1) However, if you choose to utilize a "for loop" approach, it is crucial to take the necessary precautions to avoid errors such as "buffer overflow." (im not sure if java programmers actually call it like that) Within the loop, you can then assign the value of 1 to a specific index product[i] = 1;
28th Jan 2023, 5:09 PM
Mirielle
Mirielle - avatar
+ 1
Why any other? What is the problem with the Arrays.toString(product); //Arrays.toString() other way is using loop again.
28th Jan 2023, 5:32 PM
Jayakrishna 🇮🇳
0
When i want to print the product, i use System.out.println(Array.toString(product)); Is there any option that i can use to print it?
28th Jan 2023, 5:29 PM
Aenul
Aenul - avatar
0
It not show any error and i thought there are another option to print the array😂 Sorry sorry. Anyways thanks for helping me !
28th Jan 2023, 5:34 PM
Aenul
Aenul - avatar
0
Another idea could be to use the for each loop. https://www.sololearn.com/learn/Java/2209/?ref=app
28th Jan 2023, 6:52 PM
Stefanoo
Stefanoo - avatar