1.11M Members

Java integer array reverse recursion problem

 
0
 

I want to reverse and array of integer recursively, I think this is the way but I get this error when trying with a 5 integer array:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at name.of.package.ArrayAscDesc.CambioAscDesc(ArrayAscDesc.java:12)
at name.of.package.ArrayAscDesc.main(ArrayAscDesc.java:34)

Here's the code:

import java.util.Scanner;

public class ArrayAscDesc {

    public static int[] CambioAscDesc (int[] array, int index, int tam){
        
        while(index < tam){
            
            int temp = array[index];
            array[index] = array[tam];
            array[tam] = temp;
            
            CambioAscDesc(array, index++, tam--);
        }
        return array;
    }
        
        
    
    public static void main(String[] args) {
        
        Scanner teclado = new Scanner(System.in);
        System.out.print("Inserte el tamaño del array: ");
        int tam = teclado.nextInt();
        
        int[] array = new int[tam];
        
        System.out.println("Inserte datos para un array de " + tam + " elementos:");
        for(int i=0; i<tam; i++)
        {array[i]= teclado.nextInt();}
        
        System.out.print(CambioAscDesc(array, 0, tam));
    }

}

Thanks beforehand!

 
0
 

The while on line 7 looks wrong to me. This is a recursive solution, it shouldn't need another loop. I would expect a simple if.
You'll probably want a better print on line 32, since array is an array.

 
0
 

Even changing it to an if I get the same error.

About the print, I needed to name it so I named it "array".

 
0
 

At the entry to your recursive method print the values of all the parameters so we can see where its going wrong.
To print the contents of the array you can use
System.out.println( Arrays.toString(array));

 
0
 

I have pretty much the same problem but what I need to do is a bit more complicated :/
I need to get an input like "Hello" and reverse it and the output has to be "o,lo,llo,ello,Hello"
please Help!

 
0
 

Forget the computer. Get a sheet of paper and work out how you would do this by hand. In detail. Then, and only then, write a program that does the same thing.

You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: