2017-10-19 91 views
-2

我有一個溫度轉換器分配。提供的代碼,我必須添加的東西,使其工作。我遇到的問題是,如果scale是一個字符串數組,那麼我將如何返回一個用於縮放的字符。溫度轉換器java

任何有** code **的東西都是我寫的。

public class Temperature{ 
**private double temp; 
private char scale;** 
/** different scale names */ 
public static String[] scales = {"Celsius", "Fahrenheit", "Kelvin"}; 
**scales[0] = "C"; 
scales[1] = "F"; 
scales[2] = "K";** 

public Temperature(){ 
    **temp = 0.0; 
    scale = scales[0];** 
} 



/** Initializes a temperature object with given value in Celcius 
    * 
    * If the initial temperature is less than -273.15 then the temperature 
    * object will be initialized with -273.15C. 
    * 
    * @param temp is the initial temperature in Celsius. 
    */ 
public Temperature(double temp){ 
    **this.temp = temp; 
    if(temp < (-273.15)){ 
    temp = (-273.15); 
    } 
    scale = scales[0];** 
} 


/** Initializes a temperature object with given value using the specified scale 
* <par> 
* If the temperature is lower than absolute zero, then set the temperature to 
* absolute zero (in whichever scale is specified). 
* <par> 
* Examples: new Temperature(12.3, "K") 
*   new Temperature(-90.2, "Celsius") 
* 
* @param temp is the initial temperature 
* @param scale is the scale of initial temperature and must either be 
*  one of the Strings in the <code>scales</code> array, or 
*  the first letter (capitalized) of one of those strings. 
*/ 
public Temperature(double temp, String scale){ 
    **this.temp = temp; 
    if(temp < (-273.15)){ 
    temp = (-273.15); 
    } 
    scale = scales[];** 
} 



/** The output of this getter method must always be the first letter of one 
    * of the strings in the <code>scales</code> array, capitalized. 
    * 
    * @return the current scale of the object as a single char (the first letter, 
    *   capitalized of one of the strings from <code>scales</code>) 
    */ 
    public char getScale(){ 
    return 'X'; 
    } 
+2

你可以運行它以找出是否有意義。 – Henry

+1

@亨利怎麼樣?沒有「主」。 –

+0

@DawoodibnKareem不太難爲測試添加一個,不是嗎? – Henry

回答

0

你的最後一個構造函數應該如下,按您的問題..

public Temperature(double temp,String scale){ 
    if(scale.equals("C")) 
    { 
      if(temp<-273.15) 
      { 
       this.temp=-273.15; 
      } 
      else 
       this.temp=temp; 
     } 
     else if(scale.equals("F")) 
     { 
      if(temp<-459.67) 
      { 
       this.temp=-459.67) 
      } 
      else 
       this.temp=temp; 
     } 
     else if(scale.equals("K")) 
     { 
      if(temp<0) 
      { 
       this.temp=0; 
      } 
      else 
       this.temp=temp; 
     } 
     this.scale=scale; 
    } 
+3

'if(scale ==「C」)':認真嗎?爲什麼只有在超出範圍時才設置溫度? – Henry

+0

對不起,錯字@亨利 –

+0

@ShivKumar這不是關於打字錯誤。你確定要用'=='來比較'String'嗎? –