Reputation: 3
When running it in cmd it shows error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at Reverse.main(Reverse.java:18)
My code is
import java.util.*;
class Reverse
{
public static void main (String agrs[])
{
Scanner sc = new Scanner (System.in);
int a,r,s;
System.out.print("Enter Number: ");
r= sc.nextInt();
int num[]=new int[r];
for (a=0;a<r;a++)
{
System.out.print("Enter Number: "+(a+1)+":");
num[a]=sc.nextInt();
}
System.out.println("\n Displaying number in reverse order\n-----------\n");
for (a= num[a]-1;a<0;a--)
{
System.out.println(num[a]);
}
}
}
Since I am new to java, I am confused about how to fix this.
Upvotes: 0
Views: 425
Reputation: 2649
You solved the problem thanks to mmking's answer.
Now let's think about how to print the reverse of an array using java 8 features.
Use of numeric Stream
int num[] = { 5, 6, 7, 8 };
IntStream.range(1, num.length + 1).boxed()
.mapToInt(i -> num[num.length - i])
.forEach(System.out::println);
Use of Collections.reverseOrder
Stream.of(5, 6, 7, 8).sorted(Collections.reverseOrder())
.forEach(System.out::println);
Use of descendingIterator
Stream.of(5, 6, 7, 8).collect(Collectors.toCollection(LinkedList::new))
.descendingIterator().forEachRemaining(System.out::println);
Output
8
7
6
5
Upvotes: 0
Reputation: 1575
Problem here:
for (a= num[a]-1;a<0;a--){
System.out.println(num[a]);
}
ArrayIndexOutOfBoundsException means the array does not have an index of num[a] - 1
.
Try this instead:
for (a = r - 1; a >= 0; a--){
System.out.println(num[a]);
}
Or use num.length - 1
:
for (a = num.length - 1; a >= 0; a--){
System.out.println(num[a]);
}
Upvotes: 2