【发布时间】:2018-04-09 03:01:22
【问题描述】:
我正在完成我的项目,但我无法得到我需要的答案。这就是我所拥有的。
public class Question1<T extends Comparable>
{
private static Circle[] b = {};
private T key;
public Question1(Circle[] b, T key)
{
Question1.b = b;
this.key = key;
}
/**
* @param aB the b to set
*/
public static void setB(Circle[] aB) {
b = aB;
}
/**
* @param key the key to set
*/
public void setKey(T key) {
this.key = key;
}
/**
*
* @param b
* @param low
* @param high
* @param x
* @return
*/
public String run(Circle[] b, int low, int high,int x)
{
if(low > high)
{
return "This is not a Circle.";
}
else
{
int mid = ((high + low)/2);
if(key.compareTo(b[mid].radius) == 1)
{
return run(b,mid+1,high,x++);
}
else if( key.compareTo(b[mid].radius) == 0)
{
return run(b,low,mid-1,x++);
}
return "You wanted to find Circle: " + key + " It is in element: " + b[x];
}
}
}
这是带有 compareTo() 方法的圆形对象类
public class Circle implements Comparable<Circle>
{
public double radius;
public Circle() {
}
public Circle(double r)
{
this.radius = r;
}
public void setRadius(double radius)
{
this.radius = radius;
}
@Override
public String toString()
{
return " " + radius;
}
/**
*
* @param t
* @return
*/
@Override
public int compareTo(Circle t)
{
if(this.radius < t.radius)
{
return 1;
}
else if(this.radius > t.radius)
{
return 0;
}
return 2;
}
}
这是我的启动方法
public class Start
{
public static void main(String[] args)
{
Circle[] b = {new Circle(1),new Circle(2),new Circle(3),new Circle(4),new Circle(5),new Circle(6)};
double key = 4;
Question1 qu = new Question1(b,key);
System.out.println(qu.run(b, 0, b.length,0));
}
}
问题是当我开始比较半径时。假设我创建了一个圆圈数组
Circle[] b = {new Circle(1),new Circle(2),new Circle(3),new Circle(4),new Circle(5),new Circle(6)};
我想找到一个半径为 4 的圆。但我的代码没有找到它并转到“这不是一个圆”,我认为我没有正确编码 compareTo 方法。如果不是,我可以做些什么来纠正正在发生的事情?
【问题讨论】:
-
您最初从哪里调用 run?最初可能是低>高吗?如果您没有调试器,最好使用调试器进行单步调试,这样您就可以在调用 run 时看到变量的各种状态。
-
这就是我一直在做的,我只是不明白。这是我的电话 run(b, 0, b.length,0)
-
您还没有向我们展示如何实例化您的
Question1<>类,或者如何使用您的圆圈数组调用run方法,并搜索数据。您的代码有很多问题,但如果没有看到您的全部尝试,我们甚至无法开始提供帮助。 -
我会编辑我的帖子。
-
Comparable.compareTo方法不会/不应该返回 0、1 或 2 来表示大于、小于和等于,就像您假设的那样。它应该返回 1 表示大于。查看Javadoc。而且您没有在您的 circle 类中使用 compareTo 方法,而是在您的run方法中使用java.lang.Double中的 compareTo 方法。而且您的代码还有很多其他问题(static字段b,甚至没有使用,因为您在run方法中使用了传入的参数b- 为什么它被称为 @987654334 @ 而不是search? 等)
标签: java generics recursion computer-science