簡體   English   中英

如何使用循環在java中創建表

[英]how to make tables in java using loops

在課堂上我遇到了以下問題:

編寫一個包含以下兩種方法的類:

/** 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");
        }
    }

}

問題是在“主”循環中它首先循環通過第一個循環,然后運行第二個循環。 但是為了顯示一個表,它必須在第一個循環之間進行更改。 或者我是否必須采取其他方法。

嘗試這個:

 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

那里有太多的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");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM