Re: Help with array code.
Check the semicolon after the loop...this will cause your loop to run, and only after completion the println will try to print...at which point i is equal to 5.
Re: Help with array code.
1. You have declared an array that can hold 5 int values, but you haven't put any int values into it...
2. Your 'for' loop has a misplaced semi-colon at the end of the 'for...' statement, so the loop does nothing and the print of the array item happens after the loop has finished - when index i is 5, which is past the end of the array.
ETA: D'oh! copeg got there first...
Re: Help with array code.
Fixed the semicolon and added the int values.
[CODE] public static void main (String[]args)
{
//create an array to hold 5 integers
int [] array = new int [5];
int i=0;
array[i] = i + 1;
for(i=0;i<5;i++)
System.out.println (array[i]);
}
}[CODE]
Now, I get this output with only the number 1 and the rest zeros.
output:
1
0
0
0
0
Process completed.
Re: Help with array code.
Yes, that is what your code says to do: Put a value in element 0 of the array.
Code :
int i=0; // set the value of i to 0
array[i] = i + 1; // add 1 to i (1+0 = 1) and put that in element 0 of array
What do you want your code to do?
Re: Help with array code.
@ Norm, I want the code to display 5 integers from first to last then last to first.
Re: Help with array code.
If you want your array to have 5 integers in it, you have to put 5 integers into it. The compiler can't read your mind. You've told it to put one integer into position 0, so it put one integer into position zero.
I suggest you use one loop to put the integers into the array and a couple of loops to print them out again in first-to-last and last-to-first order.