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.
6 Respostas
+ 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();
}
+ 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.
+ 2
You have just created an instance of Scanner class. Now could you take an integer input from the user using the Scanner object?
+ 1
#Avinesh Thanks a lot.
0
To take the user input, I'd use the Scanner class.
Scanner sc = new Scanner(System.in);
0
Yes.
int myInput = sc.nextInt();