Im still starting out in java - and any guidance would be great on this. I'm basically hoping to create an array, then assign values to that array in a for loop. The code I have at the moment is:
int i;
int[] testarray = new int[50];
for (i = 0; i <=50; i++) {
testarray[i]=i;
}
All i wanna do is make an array with each entry the number of the iteration (using this method) I know its really simple, but I feel as if I have missed something important during learning the basics! Thanks!
Java Array is a collection of elements stored in a sequence. You can iterate over the elements of an array in Java using any of the looping statements.
Assigning values to an element in an array is similar to assigning values to scalar variables. Simply reference an individual element of an array using the array name and the index inside parentheses, then use the assignment operator (=) followed by a value.
Everything is fine except the stop condition:
for (i = 0; i < 50; i++) {
Since your array is of size 50, and indices start at 0, the last index is 49.
You should reduce the scope of i
, avoid hard-coding the length everywhere (don't repeat yourself principle), and respect the camelCase naming conventions:
int[] testArray = new int[50];
for (int i = 0; i < testArray.length; i++) {
testArray[i]=i;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With