Thanks in advance public class toUsd {

public static void main(String[] args) { Scanner in = new Scanner(System.in); int i, n; n = in.nextInt(); int a[] = new int[n]; int temp; for(i = 0; i < n; i++) a[i] = in.nextInt(); for(i = 0; i < n; i++){ temp = a[i]; a[i] = a[n - i]; a[n - i] = a[i]; } for(i = 0; i < n; i++) System.out.println(a[i]); } 
  • * temp = a [i]; a [i] = a [n - i]; // Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 at class1.toUsd.main (toUsd.java:24) a [n - i] = temp; - Avet
  • one
    i varies from 0 to n-1. When i == 0 from a [n - i], we get a [n] - the index goes beyond the boundaries - alexlz

1 answer 1

The string for(i = 0; i < n; i++){ should be replaced with for(i = 1; i < n; i++){ Then the cycle will not fly out of the array.