对齐列 [英] Aligning columns

查看:75
本文介绍了对齐列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在列中显示以下字符串的输出:

I need to make the output of the following strings displayed in columns:

 System.out.printf("Weight of Item 1: %10d%n", ITEM_1);
 System.out.printf("Weight of Item 2: %10d%n", ITEM_2);
 System.out.printf("Weight of Item 3: %10d%n", ITEM_3);
 System.out.printf("Total Weight Kilograms: %10d%n", totalWeightKilograms);

我可以获取输入到字符串中的变量以移至所需位置.我无法获取变量之前的文本格式.基本上,我得到的输出是:

I can get the variables that are input into the string to shift to where I want. I can't get the text format before the variables. Basically, the output I get:

Weight of Item 1:         38
Weight of Item 2:         23
Weight of Item 3:         12
Total Weight Pounds:         73

我想要的是:

   Weight of Item 1:         38
   Weight of Item 2:         23
   Weight of Item 3:         12
Total Weight Pounds:         73

我需要尽可能多的字符串缩进(宽度).

I need the indentation(width) of the string as much I need it to be.

推荐答案

您可以将itemString放入数组,并使用%s指定格式长度只要您最长的String(22个字符).

You could put your item(s) and String(s) into array(s), and specify a format length with %s as long as your longest String (22 characters). Something like,

String[] msg = { "Weight of Item 1", "Weight of Item 2", "Weight of Item 3",
        "Total Weight Kilograms" };
int[] items = { ITEM_1, ITEM_2, ITEM_3, totalWeightKilograms };
for (int i = 0; i < msg.length; i++) {
    System.out.printf("%22s: %10d%n", msg[i], items[i]);
}

输出(按要求)

      Weight of Item 1:         38
      Weight of Item 2:         23
      Weight of Item 3:         12
Total Weight Kilograms:         73

这篇关于对齐列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆