我正在尝试复制从kg到lbs的转换列表,反之亦然。我找到了我想要的输出和功能代码,但是我遗漏了一些东西来将我的值与列的右边对齐。
这是我的代码:
import java.text.*;
public class KilosTwoColumn {
public static void main(String[] args) {
System.out.println("Kilograms" + "\t" + "Pounds" + "\t" + " | " + "\t" + "Pounds" + "\t" + "Kilograms");
int count = 0;
while (count < 100) {
int kilos = count * 2 + 1;
int pounds2 = (count + 4) * 5;
double pounds = kilos * 2.2;
double kilos2 = pounds2 * .453;
DecimalFormat df = new DecimalFormat("#.#");
//if (count > 1 && count < 98) {
//System.out.println("...");
//break;
//}
System.out.printf("%-17d %.1f | %7d %.2f%n", kilos, pounds, pounds2, kilos2);
count++;
}
}
}
我也试图在列表中创建一个中断三行并继续后两行。
答案 0 :(得分:0)
问题是你没有指定浮点数的宽度,只是小数位数......
例如,考虑"%-17d %.1f ..."
,它将第二个值设置为带有1个小数位的浮点值,但不指示要占用多少空间。通过将其更改为"%-17d %12.1f
,它将占用12个字符,包含1个小数。
尝试类似:
public class KilosTwoColumn {
public static void main(String[] args) {
System.out.printf("%12s %12s | %7s %12s\n", "Kilograms", "Pounds", "Pounds", "Kilograms");
int count = 0;
while (count < 100) {
int kilos = count * 2 + 1;
int pounds2 = (count + 4) * 5;
double pounds = kilos * 2.2;
double kilos2 = pounds2 * .453;
DecimalFormat df = new DecimalFormat("#.#");
//if (count > 1 && count < 98) {
//System.out.println("...");
//break;
//}
System.out.printf("%12d %12.1f | %7d %12.1f\n", kilos, pounds, pounds2, kilos2);
count++;
}
}
}
对我来说,上面的过程输出:
Kilograms Pounds | Pounds Kilograms
1 2.2 | 20 9.1
3 6.6 | 25 11.3
....
199 437.8 | 515 233.3