0

我面临的问题是了解如何利用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 类作业的一部分。请保持简单。

4

1 回答 1

0

该错误说明了一切 -binarySearch不是静态的,您正在尝试在静态函数中使用它。让它静态:

public static int binarySearch(Movie[] movies, String key) {
...

对于另一个错误,您只需要交换函数调用和变量:

x = binarySearch(movies, key);

因为binarySearch(movies, key) = x;意味着分配x给从函数返回的值(而不是相反),这没有意义,因为一旦表达式完成执行,返回的值就会消失。

而您只是输入compareTo错误(缺少e)。

于 2013-04-04T06:21:24.927 回答