简体   繁体   中英

ArrayIndexOutOfBoundsException when printing the reverse of an array

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.

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]);
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM