I have an array and "for each" loop skips the first element of it.
for (int number : nums) {
System.out.println(nums[number]);
}
Output starts from nums[1]
. What is wrong?
I have an array and "for each" loop skips the first element of it.
for (int number : nums) {
System.out.println(nums[number]);
}
Output starts from nums[1]
. What is wrong?
Please try the following code:
for (int currentNumber : nums) {
System.out.println(currentNumber);
}
I've tried renaming the variable used in the iteration so it is easier to understand how to print it / manipulate it.
For this reason when you use nums[number] at the 1st iteration you are printing nums[1]
You're accessing the array again inside the for
clause, when that is what the for
is already doing.
With that in mind, your code should look like this:
for (int number : nums) {
System.out.println(number);
}
What you were doing is access the array at the position indicated by the value from the array being read.
Hope this helps!
You're using an "enhanced for loop":
for (int number : nums) {
System.out.println(nums[number]);
}
This is equivalent to:
for (int i = 0; i < nums.length; i++) {
int number = nums[i];
System.out.println(nums[number]);
}
So you using nums[number]
means you're accessing the array with an index whose value is an element of the array. If the element at nums[0]
is 1
then the first element printed out will be the element at nums[1]
.
Note you probably meant to use:
for (int number : nums) {
System.out.println(number);
}
Whether or not this solves your problem completely is difficult to say and would depend on what you're actually trying to do.
You can get value directly in number
varible. You won't get index in number
variable. This is exact solution.
for (int number : nums) {
System.out.println(number);
}