0

我正在尝试复制从 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++;
        }
    }
}

我还试图在列表中的三行中创建一个中断并恢复最后两行。

4

1 回答 1

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
于 2013-10-16T23:41:57.170 回答