我面临的问题是了解如何利用binary search
搜索给定array
(电影)的用户输入标题?我对搜索本身有感觉,但不明白如何使用返回值来显示找到或未找到的标题。
接下来的代码段包括我bubble sort
进入binary search
. 以下是我不断看到的一些错误消息。
C:\Users\goofy bastard\Documents\JAVA>javac CharlieBrownP5.java
CharlieBrownP5.java:115: error: non-static method binarySearch(Movie[],String)
cannot be referenced from a static context
binarySearch(movies, key) = x;
CharlieBrownP5.java:115: error: unexpected type
binarySearch(movies, key) = x;
required: variable
found: value
CharlieBrownP5.java:134: error: cannot find symbol if(key.comparTo(movies[mid].getTitle()) > 0) {
symbol: method comparTo(String)
location: variable key of type String
3 errors
代码:
public static void displayTotals(Movie[] movies) {
double totalRevenue = 0;
int totalMovies = Movie.getTotalMovies();
for(int i = 0; i < movies.length; i++) {
totalRevenue += movies[i].calcRevenue();
}
System.out.print("The total number of movies is " + totalMovies +
" and their total revenue is ");
System.out.printf("%8.3f", totalRevenue);
System.out.print(" million dollars.\n\n");
}
public static void searchForMovie(Movie[] movies) {
Scanner input = new Scanner(System.in);
boolean needNextPass = true;
String key;
Movie temp;
System.out.print("Enter the Title of the Movie to Search for: ");
key = input.nextLine();
for(int pass = 1; pass < movies.length && needNextPass; pass++)
{
needNextPass = false;
for(int x=0; x< movies.length-pass; x++)
{
if(movies[x].getTitle().compareTo(movies[x+1].getTitle()) > 0)
{
temp = movies[x];
movies[x] = movies[x+1];
movies[x+1] = temp;
needNextPass = true;
}
}
}
int x;
binarySearch(movies, key) = x;
if (movies[x].getTitle() == key){
System.out.printf(movies[x].toString());
}
else{
System.out.print("There is no match item found for movie " +
"with the title " + key);
}
}
public static void getMenuChoice4() {
}
public int binarySearch(Movie[] movies, String key) {
int low = 0;
int high = movies.length -1;
while (high >= low) {
int mid = (low + high) / 2;
if(key.comparTo(movies[mid].getTitle()) > 0) {
high = mid -1;
}
else if(key == movies[mid].getTitle()){
return mid;
}
else{
low = mid + 1;
}
}
return -low - 1;
非常感谢任何帮助,我已经为此工作了几个小时。我对 java 很陌生,这是我的 java 类作业的一部分。请保持简单。