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」循環中,它首先循環第一個循環,之後循環運行第二個循環。但爲了顯示一個表格,它必須在第一個循環之間進行更改。還是必須採取其他方法?
你幾乎在那裏!你不需要那麼多循環,40-31和120-30之間常見的是什麼? – aayoubi
你在代碼中引入了一個無限循環,注意! –
修復了無限循環 –