Reputation: 27
Can someone tell me what's wrong with my array code? the output is correct, but there is some error showing at the bottom of the output.
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] number = {1,2,3,4,5};
System.out.println("Number in ascending order: ");
for (int x=0; x < number.length; ++x)
System.out.println(number[x]);
lasttofirst(number);
}
public static void lasttofirst(int[] number)
{
System.out.println("Number in descending order: ");
for (int x=4; x<number.length; --x)
System.out.println(number [x]+ " ");
}
Upvotes: 1
Views: 350
Reputation: 53657
Problem is in following logic
for (int x=4; x<number.length; --x)
when initially x= 4 it is satisfying condition x<number.length
because 4<5
then x value becomes 3 for next occurance 3<5 also satisfys
...
..
when x value becomes 0 then 0Problem occured Now x value became -1 then -1number[-1] gives you ArrayIndexOutOfBoundsException The array contains data from 0th posiiton to number of element -1 position
Instead of that logic you can use following logic
for (int x=number.length-1; x>=0; --x)
System.out.println("Index..."+x+"..."+number [x]+ " ");
}
Upvotes: 3
Reputation: 6791
I dont know really understand what you are trying to achieve with your
lastoffirst(number)
But your problem lies here-
for (int x=4; x<number.length; --x)
I can see that the value of number.length is 5 and you are decereasing your loop variable starting from a number smaller than 5. ultimatele at one stage it tries to print number [-1] which is not possible. thats why you are getting that error.
Cheers.
Upvotes: 0
Reputation: 2131
You wrongly typed your for
loop
If you want to print table elements in backwards, you have to start from last (so, length - 1, cause we index from 0), until x
is less than 0.
so it should be:
for(int i=number.length-1; x>=0; --x){
System.out.println(number[x]); // <-- also you dont need +" ", as printLN inserts new line
}
Upvotes: 1
Reputation: 500447
There's an error here:
for (int x=4; x<number.length; --x)
x<number.length
should read x >= 0
.
Upvotes: 1