Puedo ejecutar esto para eliminar un elemento de una matriz, pero ¿cómo puedo subir las películas para que no se muestre como -1, 0, 1, etc.? Esta es una captura de pantalla de salida: https ://imgur.com/a/Ab0PP3p
public static String[] removeMovies (String[] newList) { String[] removeMovies = new String [newList.length-1]; for (int i=0; i < newList.length-1; i++) { removeMovies[i]= newList [i+1]; } Scanner scan= new Scanner(System.in); System.out.println("Which movie would you like to delete?"); removeMovies[removeMovies.length-1]=scan.nextLine(); return removeMovies; } public static void dltMovieList(String[] movies) { for (int i=0; i<movies.length-1;i++) { System.out.println((i-1)+")" +movies[i]); }Aquí está mi implementación del problema:
import java.util.Scanner; class Main { public static void main(String[] args) { String[] movies = {"The Avengers","Rush Hour","Fast & Furious 7","The Ugly Truth","Spiderman"}; dltMovieList(removeMovies(movies)); } public static String[] removeMovies (String[] newList) { String[] removeMovies = new String [newList.length-1]; Scanner scan= new Scanner(System.in); System.out.println("Which movie would you like to delete?"); String movieDel = scan.nextLine(); int iterator = 0; for(int x = 0; x < newList.length; x++){ if(!newList[x].equals(movieDel)){ removeMovies[x] = newList[iterator]; } else{ iterator++; removeMovies[x] = newList[iterator]; } iterator++; } return removeMovies; } public static void dltMovieList(String[] movies) { for (int i=0; i<movies.length;i++) { System.out.println((i+1)+") " +movies[i]); } } }Ejecutar este código generará:
Which movie would you like to delete? Spiderman 1) The Avengers 2) Rush Hour 3) Fast & Furious 7 4) The Ugly TruthLa forma en que funciona este código es que, similar al suyo, creamos una nueva matriz para almacenar la lista de películas después de eliminar una película.
Luego, tomamos la entrada del usuario para averiguar qué película quieren eliminar.
Al iterar a través de nuestra matriz para copiar los valores, si nos encontramos con ese valor, lo omitimos y no lo copiamos.
Finalmente, cuando imprimamos los valores, queremos comenzar en i = 0 y subir hasta i = movies.length - 1 para obtener todos los valores. Además, cuando imprimamos el índice, debemos agregar 1 para que comencemos en 1.
¡Espero que esto haya ayudado! ¡Hazme saber si tienes alguna pregunta!