i <= nums.length is the problem
array is length 3, so valid indexes are 0,1,2, Your code executes with indexes 0,1,2,3
JamesCherrill
Posting Genius
6,371 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,073
Your loop tries to access these array elements:
nums[0], nums[1], nums[2], nums[3]
but there is no nums[3]
JamesCherrill
Posting Genius
6,371 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,073
In my opinion, that shouldn't be a problem because I haven't specified values for indexes 2 and 3. However, I changed the number of elements in my array to two elements and I'm still getting the same error. Anyway, thanks for your comment.
Unfortunately for you, in Java's opinion any attempt to reference an element bigger than the array is an error. If you have an array of 3 elements you can only refer to nums[0], nums[1], nums[2]. Any kind of reference to nums[3] is an error, whether you've specified values or not.
You still have exactly the same problem in your for loop. The way you coded it gives values for i of 0,1,2,and 3. When you use i=3 as an index for your array that's the error. Look again at your for loop, and especially it's termination condition.
JamesCherrill
Posting Genius
6,371 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,073
Was that sarcasm? I wanted you to work it out for yourself. That way you will really understand it, and never make that mistake or any variant of it again. I could have just posted a corrected version of line 3 from your original post, and you could have pasted that into your code - problem solved, nothing learned. It's the DaniWeb way.
J
JamesCherrill
Posting Genius
6,371 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,073
Hi rotten69. I'd appreciate some more detailed feedback here, because it's really difficult to get the balance between guiding/teaching someone and spoon-feeding them a quick solution. And sure, yes, I get it wrong sometimes.
Now you know the what and the why of this problem, perhaps you could post a little example of how it could have been best explained to someone in your position?
Thanks
James
ps: in case there's any doubt, this is not any kind of p*ss-take or sarcasm, it's a genuine request for feedback.
JamesCherrill
Posting Genius
6,371 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,073
try this...this syntax might not be the answers that your expecting....
public class qwe
{
public static void main(String []args)
{
int array []= {1,2,4};
for( int x = 0; x < array.length; x++)
{
System.out.println(array[x]);
}
}
}
This was exactly the issue, NewbieGuy, but JamesCherrill already explained this three times, the OP has been able to figure out what the problem was, has corrected his code and marked this thread as solved.
so .... why still post this?
stultuske
Posting Sensei
3,137 posts since Jan 2007
Reputation Points: 1,114
Solved Threads: 433