このメソッドは、オブジェクトの配列を渡すことになっています。
Movie[] movieList = new Movie[6];
movieList[0] = new Drama("Titanic","James Cameron", 1997, 200.0, 80.0, 7.50);
movieList[1] = new Drama("Fight Club", "David Fincher", 1999, 63.0, 30.0, 6.50);
movieList[2] = new Animated("Spirited Away", "Hayao Miyazaki", 2001, 19.1, 2.0, 30.0);
movieList[3] = new Animated("Toy Story", "John Lassater", 1995, 30.0, 3.5, 200.0);
movieList[4] = new Documentary("Super Size Me","Morgan Spurlock", 2004, 0.006, 35, .005);
movieList[5] = new Documentary("Jiro Dreams", "David Gelb", 2011, 0.003, 26, .002);
映画のタイトルで整理して検索することになっています。ただし、スイッチステートメントを使用してオブジェクトをメソッドに渡そうとするたびに:
case 3:
System.out.println("Please input the movie you are searching for:");
key = input.nextLine();
key = input.nextLine();
if(searchMovies(movieList, key)== -1)
{
System.out.println("There is no match found for movie with title " + key);
}
else
{
index = (searchMovies(movieList, key));
System.out.println(movieList[index].toString());
System.out.println("\n");
}
break;
返されるのは、キーが見つからなかったことを示す負の 1 か、配列インデックスが範囲外であることを示すエラーだけです。これは、バブルソートと二分探索法を含む searchMovies メソッドです。
/*-------------------------------------------------------------------------
//searchMovies first sorts the array of objects by title through Bubble
//Sort and then searches the array using Binary Search for the users
//key.
-------------------------------------------------------------------------*/
public static int searchMovies(Movie[] movieList, String key)
{
//Bubble Sort the titles
boolean needNextPass = true;
Movie temp;
for(int pass=1; pass<movieList.length && needNextPass; pass++)
{
needNextPass = false; // Array may be sorted and next pass not needed
for(int x=0; x<movieList.length-pass; x++)
if(((Profitable) movieList[x]).calcProfit() < ((Profitable) movieList[x+1]).calcProfit()) /** compare rental fee */
{
temp = movieList[x];
movieList[x] = movieList[x+1];
movieList[x+1] = temp;
needNextPass = true; // Next pass still needed
}
}//end for
//Binary search for key
int first = 0;
int last = movieList.length;
while (first <= last) {
int mid =(first + last) / 2; // Compute mid point.
if (key.compareTo(movieList[mid].getTitle()) < 0) {
last = mid; // repeat search in bottom half.
} else if (key.compareTo(movieList[mid].getTitle()) > 0) {
first = mid + 1; // Repeat search in top half.
} else {
return mid; // Found it. return position
}//end if
}//end loop
return -1; // Failed to find key
}//end searchMovies'