Reputation: 11
I have some problems with an exercise I can do to learn coding with arrays. It's basically my questions title. It's supposed to give me 9,8,7,6,...,0 but it just prints out 0,0,0,0,0,...
Can anyone see what I do wrong here?
public static void main(String[] args) {
// TODO code application logic here
int intArray[] = new int[9];
for (int i = intArray.length -1; i>=0; i--);{
System.out.println(java.util.Arrays.toString(intArray));
}
}
Upvotes: 0
Views: 223
Reputation: 746
You create array with lenght 9, but you don't set any values in it, so integer instantiated with zeros by default.
You want this:
int intArray[] = new int[]{1,2,3,4,5,6,7,8,9};
and cycle is wrong as well, reverse print should be like this:
int intArray[] = new int[]{1,2,3,4,5,6,7,8,9};
for (int i = intArray.length -1; i>=0; i--){
System.out.println(intArray[i]);
}
What you did - printed whole array. In my example I print i element of array on every iteration.
And there were extra semicolon after for(...)
UPDATE: there are another ways to get array filled with 10 digits. One more option is another for cycle:
int intArray[] = new int[10];
for (int i = 0; i < intArray.length; i++) {
intArray[i] = i;
}
for (int i = intArray.length -1; i>=0; i--){
System.out.println(intArray[i]);
}
Brings the same result, and can be more handy if you have really big array
Upvotes: 1
Reputation: 334
Your code have two error .
Run below code
public static void main(String[] args) {
//need to initalized your array
int intArray[] = new int[]{1,2,3,4,5,6,7,8,9};
for (int i = intArray.length -1; i>=0; i--){
System.out.println(intArray[i]);
}
}
Upvotes: 0