繁体   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