我正在尝试创建自己风格的Bucket排序,但我的代码出现错误,我不知道如何修复它。任何帮助都是最好的。我有两个类,Node和BucketSort:
public class Node {
protected int element;
protected Node next;
public Node()
{
element = 0;
next = null;
}
public Node getNext(Node n)
{
return next;
}
public void setNext(Node n)
{
n = next;
}
public void setElement(int e)
{
e = element;
}
public int getElement()
{
return element;
}
}和
public class BucketSort extends Node{
public static void bucketSort(int v, int[] b) //b = the array of integers and v = number of buckets wanted.
{
Node[] bucket = new Node[v]; //Creating an array of type Node called bucket with v buckets.
for (int i=0; i<=b.length; i++){
bucket[i].setElement(b[i]); //Loop through array of integers b, and set each element to the corresponding index of array bucket.
return;
}
for (int i=0; i<=bucket.length; i++){
//Getting the element at the indexed Node of array "bucket" and assigning it to the array "b" at location element-1. For example if the element is 3, then 3 is assigned to index 2, since it is the 3rd spot.
b[getElement()-1] = bucket[i].getElement();
return;
}
System.out.println(b);
}
}我在BucketSort的第16行收到以下错误,is代码: bgetElement()-1
错误是:
无法从类型Node对非静态方法getElement()进行静态引用。
你能告诉我怎么解决这个问题吗。
谢谢
如何测试此程序?
发布于 2010-09-15 11:23:52
问题在于您滥用了static关键字。我不确定您是否熟悉Java语言中静态方法的语义(如果您不熟悉,您应该阅读一些全面的资料,也许是starting here),但基本思想是声明为static的方法或字段属于类,而不是该类的任何特定实例(对象)。特别是,static方法没有任何this指针的概念。
所以问题是,当你的代码自己调用getElement()时,Java会隐式地将其解释为this.getElement()。但是,bucketSort()是static,而getElement()属于Node的一个实例,所以这没有任何意义--调用getElement()的确切原因是什么?
在特定的Node对象上调用它,比如bucket[i],它就会编译(虽然还没有真正看到它是否能工作)。
发布于 2010-09-15 11:36:23
查看错误。它会告诉你所犯的错误。
您可以为特定对象调用getElement()。
为什么bucketSort(int v, int[] b)需要是静态的?有什么原因吗?
https://stackoverflow.com/questions/3714418
复制相似问题