2015-04-25 78 views
0

我遇到了調用不同類中的方法的問題。該方法在其自己的lab14類別中,heapSort()方法位於不同的類別HeapSort中。這兩個類都在默認包中。我收到錯誤「The method heapSort(Vector)is undefined for the Lab14」,我不明白爲什麼,請幫忙。Java該方法對此類型未定義

下面

是在實驗室的主要方法14類

public static void main(String args[]) { 

    Heap myheap = new Heap(); 
    Vector<StudentGPA> vec = new Vector(); 
    int [] br = new int[20]; 
    double [] dr = new double[20]; 
    int i = 0; 
    int j = 0; 
    try { 
    //String inputLine; //stores each line from the file 
    Scanner scanLine; 
    Scanner input = new Scanner(new File("students.in")); 
    while (input.hasNextLine()){ 
    scanLine = new Scanner(input.nextLine()); 

    int id = scanLine.nextInt(); 
    //br[i] = id; 
    String name = scanLine.next(); 
    double gpa = scanLine.nextDouble(); 
    //dr[i]= gpa; 
    //myStr.add(name); 
    if(scanLine.hasNext()) 
    { 
     String advisor = scanLine.next(); 
     GraduateStudentGPA grad = new GraduateStudentGPA(id,name,gpa,advisor); 
     vec.add(grad); 
    } 
    else 
    { 
     StudentGPA reg = new StudentGPA(id,name,gpa); 
     vec.add(reg); 
    } 
    i++; 
    j++; 
    } 
    input.close(); 
} 
catch (IOException e) { 
    System.out.println("IOException in reading input file!!!"+e); 
} 
heapSort(vec); 
} 

下面是對堆排序類

public class HeapSort <E extends Comparable<? super E>>{ 
/** sorts the input vector using heap Sort <ul> <li> iterates 
* through each element of the input vector and inserts each 
* element to the heap by calling {\tt heapInsert}. <li> deletes 
* each of the inserted items by calling {\tt heapDelete} the 
* appropriate number of times, and fills up the vector with the 
* returned elements. </ul> If you are using the 
* minheap implementation, this insertion and deletion of all 
* items will produce a list of items sorted by their key 
* attribute values. 
* @param vec input vector 
*/ 
public void heapSort(Vector<StudentGPA> vec){ 
    // -- TO COMPLETE -- 
    Heap myheap = new Heap<E>(); 
    for(int i = 0; i <vec.size(); i++) 
    { 
     myheap.heapInsert(vec.elementAt(i)); 
    } 
    for(int i = 0; i <vec.size(); i++) 
    { 
     vec.setElementAt((StudentGPA) myheap.heapDelete(), i); 
    } 

} 


} 

回答

0

代碼你答曰:

你想方法從Lab14類調​​用heapSort方法,但heapSort方法在不同的類上定義。必須編譯錯誤這個line.-

heapSort(vec); 

您需要實例化一個堆排序對象,然後調用其heapSort方法類似this.-

HeapSort myHeapSortObject = new HeapSort(); 
myHeapSortObject.heapSort(vec); 
0

你堆排序方法可以聲明爲static,至少在當前狀態下

public static <E extends Comparable<? super E>> void heapSort(Vector<StudentGPA> vec) { 

然後,您可以訪問它在你的主要方法是這樣

HeapSort.heapSort(vec); 
0

您需要:

1)使堆排序方法public 靜態 ...並調用它作爲HeapSort.heapSort(VEC)

或 2)調用的方法作爲新的HeapSort()。heapSort(vec)

0

這裏有幾個問題。

  1. 你叫heapSort(vec);Lab14類的靜態main內。這意味着編譯器期望在Lab14類中匹配簽名static void heapSort(Vector<StudentGPA> vec)的方法。由你決定如何解決這個問題。
  2. Vector<StudentGPA> vec = new Vector();更改爲Vector<StudentGPA> vec = new Vector<>();。請注意,除了尖括號<>
  3. 實際上還有更多的問題,可能是因爲它仍然是一個未完成的工作。可能我應該把注意力集中在你原來的問題上,其中1. /是答案。
相關問題