gpt4 book ai didi

java - 删除元素后向上移动连续索引

转载 作者:行者123 更新时间:2023-12-05 08:04:03 25 4
gpt4 key购买 nike

我可以运行它以从数组中删除一个元素,但是我怎样才能将电影向上移动,这样它就不会显示为 -1、0、1 等...这是屏幕截图输出: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]);
}

最佳答案

这是我对问题的实现:

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]);
}
}
}

运行这段代码会输出:

Which movie would you like to delete?
Spiderman
1) The Avengers
2) Rush Hour
3) Fast & Furious 7
4) The Ugly Truth

这段代码的工作原理是,与您的类似,我们在删除电影后创建一个新数组来存储电影列表。

然后,我们根据用户输入找出他们想要删除的电影。

当遍历我们的数组以复制值时,如果我们遇到该值,我们将跳过它而不复制它。

最后,当我们打印出值时,我们希望从 i = 0 开始,一直上升到 i = movies.length - 1 这样我们就可以得到所有的值的值(value)观。此外,当打印出索引时,我们应该加 1,以便我们从 1 开始。

希望对您有所帮助!如果您有任何问题,请告诉我!

关于java - 删除元素后向上移动连续索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70330019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com