0

How do you fill in an array in Java using for loops?

Hello guys. I'd really appreciate if someone could answer my question? I'm stuck trying to fill an array in Java using the for loop and if you had to choose between for and while loops which one would you choose and for what reason? Thanks.

6th May 2020, 12:01 PM
Albin Sopaj
Albin Sopaj - avatar
6 ответов
+ 1
Albin Sopaj very nice, so you know how to do that. Now you can do this for taking array input. This is just an example- int[] arr = new int[5]; for(int i=0; i<arr.length; i++){ arr[i] = sc.nextInt(); }
6th May 2020, 12:29 PM
Avinesh
Avinesh - avatar
+ 3
Albin Sopaj would you mind showing me how do you take user input in Java? If that's known then populating an array wouldn't be a big task. Also I would use a for loop because arrays are static and the number of elements to be stored are known beforehand. While loops are generally used when number of iterations are not known.
6th May 2020, 12:14 PM
Avinesh
Avinesh - avatar
+ 2
You have just created an instance of Scanner class. Now could you take an integer input from the user using the Scanner object?
6th May 2020, 12:18 PM
Avinesh
Avinesh - avatar
+ 1
#Avinesh Thanks a lot.
6th May 2020, 12:30 PM
Albin Sopaj
Albin Sopaj - avatar
0
To take the user input, I'd use the Scanner class. Scanner sc = new Scanner(System.in);
6th May 2020, 12:15 PM
Albin Sopaj
Albin Sopaj - avatar
0
Yes. int myInput = sc.nextInt();
6th May 2020, 12:24 PM
Albin Sopaj
Albin Sopaj - avatar