我正在尝试创建我自己的桶排序风格,但我的代码出现错误,我不知道如何修复它。任何帮助都会很棒。我有两个类,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 行收到以下错误,代码为:b[getElement()-1]
错误是:
不能从类型 Node 对非静态方法 getElement() 进行静态引用。
你能告诉我如何解决这个问题吗?
谢谢
我如何测试这个程序?
最佳答案
问题是您误用了 static
关键字。我不确定你是否熟悉 Java 中静态方法的语义(如果你不熟悉,你应该阅读一些关于它的全面内容,也许 starting here ),但基本思想是一个方法或字段被声明为 static
属于 类 而不是该类的任何特定实例(对象)。特别是,static
方法没有任何this
指针的概念。
所以问题在于,当您的代码自行调用 getElement()
时,Java 会隐式地将其解释为 this.getElement()
。但是,bucketSort()
是 static
而 getElement()
属于 Node
的一个实例,所以这不是没有任何意义——调用 getElement()
的到底是什么?
在特定的 Node
对象上调用它,比如 bucket[i]
,它会编译(虽然还没有真正看到它是否会工作)。
关于Java 桶排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3714418/