关于作业的一些背景知识:"移动设备是杆或鲍勃。一根杆包含两个更简单的手机。 Bob不包含任何手机。当您在Mobiles上实现一个方法时,您需要有一个用于bobs的盒子和一个用于杆子的盒子。在极限情况下,您将编写一个递归情况,进行两次递归调用。例如,您需要弄清楚如何根据它支持的两个移动设备的重量来定义杆的重量。在bob的情况下,你将编写一个没有递归的基本案例。"我无法更改方法的存根,只包含其中包含的内容,我尝试启动isBalanced ()
方法,但我并不知道我要去哪里。当杆的左距离和从左端悬挂的重量的乘积等于其正确距离和从其右端悬挂的重量的乘积时,杆是平衡的。上面显示的手机中的每根杆都是平衡的,所以我们说整个手机是平衡的。如果有人能指出我正确的方向,我将非常感激。
/**
* A Mobile is either a Bob or Rod.
*
* A Bob is a Mobile consists of a weight hanging from a vertical wire.
*
* Here's a diagram, where W denotes a weight:
*
* <pre>
* |
* W
* </pre>
*
* A Rod is a Mobile that consists of a horizontal rod that has one Mobile hanging from its left end and another Mobile
* hanging from its right end. The rod is hanging from a vertical wire. The distance along the rod from the vertical
* wire to the left end is called the left length, and the distance from the vertical wire to the right end is called
* the right length.
*
* Here's a diagram:
*
* <pre>
* _____|__________
* | |
* L R
* </pre>
*
* The left length is 5 and the right length is 10. L and R are the left and right Mobiles, respectively.
*/
public class Mobile
{
/**
* True if the Mobile is a Bob; false if the Mobile is a Rod.
*/
private boolean isBob;
/**
* If isBob is true, contains the weight of the Bob.
*/
private int weight;
/**
* If isBob is false, contains the left length of the Rod.
*/
private int leftLength;
/**
* If isBob is false, contains the right length of the Rod.
*/
private int rightLength;
/**
* If isBob is false, contains the left Mobile of the Rod.
*/
private Mobile left;
/**
* If isBob is false, contains the right Mobile of the Rod.
*/
private Mobile right;
/**
* Creates a Bob with the given weight.
*/
public Mobile (int weight)
{
this.isBob = true;
this.weight = weight;
}
/**
* Creates a Rod of the given configuration.
*/
public Mobile (int leftLength, int rightLength, Mobile left, Mobile right)
{
this.isBob = false;
this.leftLength = leftLength;
this.left = left;
this.rightLength = rightLength;
this.right = right;
}
public boolean isBalanced ()
{
return false;
}
答案 0 :(得分:0)
您应该首先将您的Mobile类拆分为Rod和Bob的不同子类。在下一步中,您可以为这两种类型定义不同的isBalanced()方法。鲍勃总是保持平衡,对于罗德,你必须递归地分析左右移动。如果递归到Bob,递归会自动停止。 您需要确定移动设备是否平衡所需的左移动设备或右移动设备的总重量也必须递归计算。