[英]4 columns in java from two different loops
我需要將4列連接在一起的幫助,我已經嘗試了幾個小時,沒有其他想法了:
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 void main(String[] args) {
for ( double x = 40; x >= 31; x--){
System.out.printf("%10.1f%10.1f\n", x, celsiusToFahrenheit(x));
}
for ( double y = 120; y >= 30; y -= 10){
System.out.printf("%-10.1f%-5.1f\n", y, fahrenheitToCelsius(y));
}
}
public static double celsiusToFahrenheit(double celsius){
return (9.0/5) * celsius + 32;
}
public static double fahrenheitToCelsius(double fahrenheit){
return (5.0 / 9) * (fahrenheit - 32);
}
任何幫助表示贊賞。
您可以使用第一個循環來構建String
數組,然后在第二個循環中打印它。 就像是,
public static void main(String[] args) {
String[] arr = new String[40 - 30];
int i = 0;
for (double x = 40; x >= 31; x--) {
arr[i++] = String.format("%10.1f%10.1f", x,
celsiusToFahrenheit(x));
}
i = 0;
for (double y = 120; y >= 30; y -= 10) {
System.out.printf("%s\t %-10.1f%-5.1f%n", arr[i++], y,
fahrenheitToCelsius(y));
}
}
輸出是
40.0 104.0 120.0 48.9
...
我不確定您要通過結合這些值來實現什么。 試試這個
for ( double x = 40, y=120; x >= 31; x--, y-=10){
System.out.printf("%10.1f%10.1f", x, celsiusToFahrenheit(x));
System.out.printf("%10.1f%10.1f\n", y, fahrenheitToCelsius(y));
}
這可能是組合結果的最簡潔方法,可以隨時添加更可靠的循環終止條件
您是否嘗試過使用ArrayList<StringBuilder>
組合? 或Vector<StringBuffer>
(如果需要是線程安全的)。
基本上首先構建您的輸出,然后在完成后顯示結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.