java在数组达到极限时展开数组
我有一个程序,需要在数组中打印出几个Movie
对象(仅由单个字符串表示)。我从一个已经有五部电影的文本文件开始,但在控制台中,我允许用户根据需要扩展数组。(我无法在此问题中使用arraylist)。我曾试图设计一个程序来实现这一点,但每次尝试添加新电影时,我都会遇到一个越界异常。我还需要检查数组,看看里面是否有重复的电影对象?我该怎么做
问题:我如何允许用户扩展阵列并向列表中添加更多电影?如何检查数组以查看其中是否已经有某个电影标题强>
public class MovieDriver {
//variable declaration
static Movie[] movies = new Movie[5];
static Scanner scan = new Scanner(System.in);
static int input = 0;
static String title = "";
public static void main(String[] args) throws FileNotFoundException {
//retrieves movie data
getData();
System.out.println("Welcome to the favorite movie program.");
do{
System.out.println("Press 1 to print the list, 2 to add another movie, 3 to end the program.");
input = scan.nextInt();
switch(input) {
case 1:
for(int i = 0; i < movies.length; i++)
{
System.out.println(movies[i].toString());
}
break;
case 2:
System.out.println("Please enter the movie you would like to add to the list:");
title = scan.nextLine();
movies = Arrays.copyOf(movies, movies.length+1);
movies[movies.length] = new Movie(title);
break;
case 3:
System.out.println("Program terminated.");
break;
}
} while (input != 3);
}
// method to retrieve data
public static void getData() throws FileNotFoundException {
// reads in movie data
File MovieData = new File("./src/Movies.txt");
Scanner fileScanner = new Scanner(MovieData);
int i = 0;
// while there is a new line in the data, goes to the next one
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
Scanner lineScanner = new Scanner(line);
String title = lineScanner.nextLine();
// creates a movie
movies[i] = new Movie(title);
i++;
}
}
}
# 1 楼答案
要展开数组,必须重新创建所需大小的数组,并将以前数组的内容复制到新数组
# 2 楼答案
要将阵列扩展1,请执行以下操作:
要检查是否存在重复的电影对象,请在
Movie
类中实现equals
。然后遍历现有的电影,并检查movies[i].equals(newMovie)
# 3 楼答案
第一个问题:IndexAutofBond
不需要使用
System.arraycopy()
。 对Arrays.copyOf()
使用正确的方法。问题来自于调用
copyOf()
后,数组的新长度为6。当您执行movies[movies.length]=...
操作时,您尝试访问第7个元素。只要做:但是
Scanner
还有第二个问题。当您使用nextInt()
扫描输入时,不会读取行尾。这意味着如果输入2(添加电影),将读取2,但不会读取新行。然后新行被title = scan.nextLine()
读取,您有一个空标题。。。 解决办法是:第二个问题:检查副本
由于您只有一个普通/本机数组,并且电影之间没有排序,因此可以实现一个简单的for循环,如:
并添加一个函数(假设有一个
Movie#getTitle()
):