Home > OS >  I want to reverse an array but dont know why this error comes?
I want to reverse an array but dont know why this error comes?

Time:11-23

i dont kow ehy my programs dont run. i am trying to reverse my array through user defined function. i can give an input but cannot find out the answer.

import java.util.*;
public class reverseanarray{
public static int reversea(int array[]){
    int swap;
    int j=array.length;
    for(int i=0;i<array.length/2;i  ){
        swap=array[i];
        array[i]=array[j];
        array[j]=swap;
        j--;
    }
    return j;
}      
public static void main(String args[]){
   Scanner sc = new Scanner(System.in);
   //System.out.println();
   //int a = sc.nextInt();
   System.out.println("please input the length");
   int y=sc.nextInt();//INPUT OF LENGTH OF ARRAY
   int arr[]=new int[y];
       //INPUT ARRAY
       for(int r=0;r<arr.length;r  ){
           System.out.println("please input the " r " index value");
           arr[r]=sc.nextInt();
       }
       System.out.println(reversea(arr));
       for(int i=0;i<y;i  ){
        System.out.println(arr[i]);
       }
      
    }

}

CodePudding user response:

The code is giving you an ArrayIndexOutOfBoundsException, as you are trying to address an array index which is beyond array limits. The reason for this is, that arrays are 0-indexed, so an array of length 10 has indexes 0-9. Your code does not take this into account when defining field j.

The only change you need to make is change that line:

int j = array.length;

into this one:

int j = array.length - 1;

You could also do some more refactoring and rewrite method as:

public static int[] reversea(int array[]) {
    int swap;
    for (int i = 0, j = array.length-1; i < j; i  , j--) {
        swap = array[i];
        array[i] = array[j];
        array[j] = swap;
    }
    return array;
}

Instead of returning useless value of j after reversing, the refactored method returns the array in reversed order.

PS: Please use CamelCase for your class names.

  • Related