2015-09-15 46 views
3

在課堂上,使在Java中的表我有以下問題:如何使用循環

編寫包含如下因素兩種方法的類:

/** Convert from Celsius to Fahrenheit */ 
public static double celsiusToFahrenheit(double celsius) 

/** Convert from Fahrenheit to Celsius */ 
public static double fahrenheitToCelsius(double fahrenheit) 

The formula for te conversion is: 
fahrenheit = (9.0/5) * celsius + 32 
celsius = (5.0/9) * (fahrenheit - 32) 

編寫調用這些方法來顯示測試程序日以下表格:

celsius Fahrenheit | Fahrenheit celsius 
___________________________________________ 
40.0 104.0 | 120.0 48.89 

39.0 102.2 | 110.0 43.33 

... 

32.0 89.6 | 40.0 4.44 

31.0 87.8 | 30.0 -1.11 

我曾嘗試下面的代碼:

public static double celciusToFahrenheit(double celcius) { 
    double fahrenheit = (9.0/5) * celcius + 32; 
    return fahrenheit; 
} 

public static double fahrenheitToCelcius(double fahrenheit) { 
    double celcius = (5.0/9) * (fahrenheit - 32); 
    return celcius; 
} 
public static void main(String[] args) { 
    // TODO Auto-generated method stub 

    System.out.println("Celcius\tFahrenheit\t|\tFahrenheit\tCelcius"); 

    for (int i = 0; i < 10; i++) { 
     for (int a = 40; a > 30; a--) { 
      System.out.print(i + "\t" + celciusToFahrenheit(i) + "\t|\t"); 
     } 
     for (int b = 120; b > 30; b -= 10) { 
      System.out.print(i + "\t" + fahrenheitToCelcius(i) + "\n"); 
     } 
    } 

} 

問題是,在「main」循環中,它首先循環第一個循環,之後循環運行第二個循環。但爲了顯示一個表格,它必須在第一個循環之間進行更改。還是必須採取其他方法?

+0

你幾乎在那裏!你不需要那麼多循環,40-31和120-30之間常見的是什麼? – aayoubi

+0

你在代碼中引入了一個無限循環,注意! –

+0

修復了無限循環 –

回答

0

你在那裏有太多的for循環。你只需要一個:

for (int i = 0; i < 10; i++) { 
    double celcius = 40 - i; 
    double convertedCelcius = celciusToFahrenheit(celcius); 
    double fahrenheit = 120 - (i * 10); 
    double convertedFahrenheit = fahrenheitToCelcius(fahrenheit); 

    System.out.print(celcius + "\t" + convertedCelcius + "\t|\t" + fahrenheit + "\t" + convertedFahrenheit + "\n"); 
} 
0

試試這個:

for (int i = 0; i < 10; i++) { 
     System.out.print((40-i) + "\t" + celciusToFahrenheit((40-i)) + "\t|\t"); 

     System.out.print((120 - (i * 10)) + "\t" + fahrenheitToCelcius((120 - (i * 10))) + "\n"); 
    } 
} 

編輯:

下面是完整的代碼:http://ideone.com/q9o5G2