I am trying to remove a specific movie from the array based on user input but the output is kind of wonky, all elements are supposed to be shifted up and I'm not sure what's wrong. output: https://imgur.com/WMl38TR
private static void listMovies() {
String[]movies = {"The Avengers","Rush Hour","Fast & Furious 7","The Ugly Truth","Spiderman"};
for(int i=0; i<movies.length; i ) {
System.out.println((i 1) ") " movies[i]);
}
}
private static void removeMovies (String[] movies) {
reenterUser();
String[] deleteMovies = new String [movies.length-1];
Scanner input =new Scanner(System.in);
System.out.println("Which movie would you like to delete?");
String movieDel = input.nextLine();
for(int i = 0; i < movies.length; i ){
if (!movies[i].equals(movieDel)) {
deleteMovies[i]=movies[i];
i ;
}
System.out.println("You have deleted a movie!");
System.out.println("This is an updated list of movies available at the rental store: ");
printMoviesDeleted(deleteMovies);
}
private static void printMoviesDeleted(String[]movies) {
for (int i=0; i<movies.length;i ) {
System.out.println((i 1) ") " movies[i]);
}
}
CodePudding user response:
Need a separate variable to specify the index in deleteMovies.
int j = 0;
for(int i = 0; i < movies.length; i ){
if (!movies[i].equals(movieDel)) {
deleteMovies[j]=movies[i];
j ;
}
}
CodePudding user response:
You almost got your delete function correct, but you're incrementing i twice in the delete for loop which is causing your strange output. You need to index the deletedMovies array with a separate index like this:
private static void removeMovies (String[] movies) {
reenterUser();
String[] deleteMovies = new String [movies.length - 1];
Scanner input =new Scanner(System.in);
System.out.println("Which movie would you like to delete?");
String movieDel = input.nextLine();
int j = 0;
for(int i = 0; i < movies.length; i ) {
if (!movies[i].equals(movieDel)) {
deleteMovies[j ] = movies[i];
}
}
System.out.println("You have deleted a movie!");
System.out.println("This is an updated list of movies available at the rental store: ");
printMoviesDeleted(deleteMovies);
}