所以我有一个由名为 Vehicle 的类实现的接口(interface),该类接受 double 值作为参数:
public class Vehicle implements Efficiency
{
//instance variable
private double efficiency;
public Vehicle(double x)
{
//parameter initializes the instance variable
x = efficiency;
}
这是界面:
public interface Efficiency
{
double getEfficiency();
}
我需要创建一个名为 getFirstBelowT() 的方法,该方法接受 Efficiency 数组和 double 作为参数。该方法应该返回一个 Efficiency 对象,该对象是数组中小于参数中的 double 值的第一个对象。如何将效率数组中的元素与 double 值进行比较?这是我到目前为止所拥有的:
//a method that returns an Efficiency object that is the first
//object in the array with a efficiency below the double parameter
public static Efficiency getFirstBelowT(Efficiency[] x, double y)
{
//loop through each value in the array
for(Efficiency z: x)
{
//if the value at the index is less than the double
if(z < y)
{ //returns the first value that is less than y and stops looping
// through the array.
return z;
break;
}
}
//returns null if none of the element values are less than the double
return null;
}
最佳答案
你基本上就在那里:
您需要在条件中调用
getEfficiency
方法:if(z.getEfficiency() < y)
去掉
return
之后的break
:这是无法访问的代码。
关于以包含接口(interface)对象的数组作为参数的 Java 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33336450/