2015-10-25 58 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

雅,我忘了這麼做。我得到它的工作。非常感謝你。 –

相關問題