我面临的问题是了解如何利用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;
最佳答案
该错误说明了一切-binarySearch
不是静态的,您正尝试在静态函数中使用它。只需使其静态:
public static int binarySearch(Movie[] movies, String key) {
...
x = binarySearch(movies, key);
binarySearch(movies, key) = x;
的意思是将x
分配给从函数返回的值(不是相反),这没有意义,因为一旦该表达式完成执行,返回的值就会消失。compareTo
错误(缺少e
)。
https://stackoverflow.com/questions/15803295/