我在调用不同类中的方法时遇到问题。此main
方法本身位于一个名为lab14
的类中,heapSort()
方法位于另一个名为HeapSort
的类中。这两个类都在默认包中。我收到错误“方法heapSort(Vector)未定义为Lab14类型”,我不明白为什么,请帮忙。
是实验室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);
}
以下是HeapSort类的代码
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 :(得分:0)
你给出了答案:
您尝试从heapSort
类调用Lab14
方法,但heapSort
方法是在另一个类上定义的。编译错误必须在此行.-
heapSort(vec);
您需要实例化一个HeapSort对象,然后像这样调用它的heapSort
方法.-
HeapSort myHeapSortObject = new HeapSort();
myHeapSortObject.heapSort(vec);
答案 1 :(得分:0)
您的heapsort方法可以声明为静态,至少在当前状态
public static <E extends Comparable<? super E>> void heapSort(Vector<StudentGPA> vec) {
然后,您可以在主要方法中访问它,如此
HeapSort.heapSort(vec);
答案 2 :(得分:0)
您需要:
1)使heapSort方法公共 静态 ...并将其作为HeapSort.heapSort(vec)调用
或 2)将方法调用为新的HeapSort()。heapSort(vec)
答案 3 :(得分:0)
这里有几个问题。
heapSort(vec);
的静态main
内拨打Lab14
。这意味着编译器需要一个匹配static void heapSort(Vector<StudentGPA> vec)
类中的签名Lab14
的方法。由你决定如何解决这个问题。Vector<StudentGPA> vec = new Vector();
更改为Vector<StudentGPA> vec = new Vector<>();
。请注意,添加了尖括号<>
。