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!
Advertisement
Answer
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; }