La eliminación de un elemento de matriz en tiempo de ejecución en Java

Robert:

¿Hay una manera de quitar un elemento de una matriz de una en tiempo de ejecución?

Por ejemplo:

int[] num =  {8, 1, 4, 0, 5};

Output:
Enter the Index: 0
1, 4, 0, 5
Enter the Index: 3
1, 4, 0
Enter the Index: 1
4, 0;

Sé que no se puede cambiar el tamaño de la longitud de una matriz, una vez que se ha inicializado y en este tipo de problema de muestra, utilizando una ArrayListes mucho más práctico. Sin embargo, hay una manera de hacer este tipo de problema utilizando simplemente una matriz?

Me las he arreglado para eliminar uno de los elementos y mostrar la matriz -1 mediante la creación de nueva matriz y la copia de los valores de la matriz original en ella. Pero el problema es, en la siguiente iteración de la salida todavía puedo eliminar un elemento, pero el tamaño no cambia.

Esto es lo que pasa:

int[] num =  {8, 1, 4, 0, 5};

Output:
Enter the Index: 0
1, 4, 0, 5  // in the first loop it goes as I want it.
Enter the Index: 2
1, 4, 5, 5  // this time array's length is still 4 and just duplicates the last value
Enter the Index: 1
1, 5, 5, 5  // length is still the same and so on.

Este es mi código en la eliminación de un elemento de una matriz:

public static int[] removeElement(int index, int[] n) {

    int end = n.length;

    for(int j = index; j < end - 1; j++) {
        n[j] = n[j + 1];            
    }
    end--;

    int[] newArr = new int[end];
    for(int k = 0; k < newArr.length; k++) {
        newArr[k] = n[k];
    }

    displayArray(newArr);        

    return newArr;
}

public static void main(String[] args) {
     Scanner input = new Scanner(System.in);
     int[] num = {8, 1, 4, 0, 5};

     for(int i = 0; i < num.length; i++) {
          System.out.print("Enter the Index: ");
          int index = input.nextInt();
          removeElement(index, num);
     }
}

public static void displayArray(int[] n) {
     int i = 0;
     for(; i < n.length - 1; i++) {
          System.out.print(n[i] + ", ");
     }
     System.out.print(n[i]);
}

¿Hay un truco de cómo hacer esto en matrices? O es lo que realmente tengo que usar ArrayList?

Eran :

Usted va a desechar la nueva matriz devuelta por removeElement.

Cambiar su bucle a:

for(int i = 0; i < num.length; i++) {
     System.out.print("Enter the Index: ");
     int index = input.nextInt();
     num = removeElement(index, num);
}

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=184078&siteId=1
Recomendado
Clasificación