I am able to run this in order to delete an element from an array, but how can I shift the movies up so it doesn't display as -1, 0, 1, etc... This is a screenshot of output: 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]);
}
Here is my implementation of the problem:
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]);
}
}
}
Running this code will output:
Which movie would you like to delete?
Spiderman
1) The Avengers
2) Rush Hour
3) Fast & Furious 7
4) The Ugly Truth
How this code works is that, similar to yours, we create a new array to store the movie list after the deletion of a movie.
Then, we take user input to find out what movie they want to delete.
When iterating through our array to copy over the values, if we run into that value, we skip it and don't copy it over.
Finally, when we print out the values, we want to start at i = 0 and go up until i = movies.length - 1 so that we get all of the values. Additionally, when print out the index, we should add 1 so that we start at 1.
I hope this helped! Let me know if you have any questions!