Error in array indexes

1

Because the index i of the first for reaches i>0 and because the index i of the main class reaches i>=0 ? because if I put in the first for i>=0 I get an error when executing.

public String[] invertirArray(String[] palabrasPaInvertir) {
        String[] cadenaInvertida = new String[palabrasPaInvertir.length-1];
        int j=0;
          for (int i = palabrasPaInvertir.length-1; i > 0; i--) {

            cadenaInvertida[j] =  palabrasPaInvertir[i];
             j++;
        }
        return cadenaInvertida;
    }

 public static void main(String[] args) {
        ArregloDeCadenas arreglo = new ArregloDeCadenas();

        String[] aux1={"mundo","viva","hola"};
        String[] cadena = arreglo.invertirArray(aux1);

          for (int i =aux1.length-1; i >=0 ; i--) {
           System.out.println(aux1[i]);
        }
    }
    
asked by mac 10.06.2017 в 04:47
source

2 answers

3

This line

String[] cadenaInvertida = new String[palabrasPaInvertir.length-1];

You tell the array cadenaInvertida that it will have a length of lenght - 1. If the array palabrasPaInvertir has 9 (0 to 8 in indexes) the array cadenaInvertida will have 8 (from 0 to 7 in indexes) . Therefore, it will fail to go through the for cycle. You have to assign the long equal to the main arrangement.

String[] cadenaInvertida = new String[palabrasPaInvertir.length];

Another way to reveal the fix is to use List and use the function Collections.reverse

List<String> cadenaInvertida  = Arrays.asList(palabrasPaInvertir);
Collections.reverse(list);
System.out.println(cadenaInvertida);
    
answered by 10.06.2017 / 05:01
source
2

Because you create an arrangement with 1 less length:

String[] cadenaInvertida = new String[palabrasPaInvertir.length-1];

Serious:

String[] cadenaInvertida = new String[palabrasPaInvertir.length];
    
answered by 10.06.2017 в 04:54