2015-10-25 59 views
1

所以,我有与接口,其是由一个接受双值作为参数的一类称为车辆实现:Java方法用含有阵列接口对象作为参数

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作为参数。该方法应该返回效率对象,该对象是数组中第一个小于参数中double值的对象。如何将Efficiency数组中的元素与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; 
} 
+2

“参数初始化实例变量”否:效率= x会初始化成员变量,您将用零覆盖参数值。 –

回答

1

你基本上有:

  1. 你需要调用getEfficiency方法在有条件的:

    if(z.getEfficiency() < y) 
    
  2. 获取在return之后摆脱break:无法访问的代码。

+0

雅,我忘了这么做。我得到它的工作。非常感谢你。 –

相关问题