-4

I want to print the array in reverse order but I don't know why it's not working. I want to reverse them using the way I have mentioned below, in a single line, but my logic is not working.

void dynamicinputArraytwo() throws IOException  {

    int buffer;
    int i,jo,io;
    System.out.println("Enter size");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    buffer = Integer.parseInt(br.readLine());
    float arrtwo[]=new float[buffer];

    for( i=0;i< arrtwo.length;i++){
        System.out.println ("Enter elements of array=");
        arrtwo[i] = Float.parseFloat(br.readLine());
    }

    for (int jx=0; jx < arrtwo.length; jx++){
        System.out.println("array before reverse "+arrtwo[jx] + " ");
    }

    float arrthree[];
    arrthree = new float[arrtwo.length];

    for(io=0,jo=arrtwo.length; jo>=0;io++,jo--){
        arrthree[io] = arrtwo[jo] ;
    }

    for(io=0; io < arrtwo.length; io++){
        arrtwo[io] = arrthree[io] ;
    }

    for (int jx=0; jx < arrtwo.length; jx++){
        System.out.println("array after reverse "+arrtwo[jx] + " ");
    }
}
khelwood
  • 55,782
  • 14
  • 81
  • 108

1 Answers1

1

Your first problem is here:

for(io=0,jo=arrtwo.length; jo>=0;io++,jo--){
    arrthree[io] = arrtwo[jo] ;
}

The last index of an array is length - 1 because arrays are indexed starting at 0, so you'll have an exception (i.e. arrtwo[arrtwo.length] is not a valid index in the array). You should set jo to arrtwo.length - 1 initially instead.