适当的数据格式和对齐方式

huangapple go评论101阅读模式
英文:

Proper data formatting and alignment

问题

如何正确格式化这些数字列?意思是所有数字应该在列中对齐。

我尝试使用格式化但仍然无法修复对齐。例如:

  1. 625 50 25
  2. 676 52 26
  3. 729 54 27
  4. 784 56 28
  5. 841 58 29
  6. 900 60 30
  7. 961 62 31
  8. 1024 64 32
  9. 1089 66 33
  10. 1156 68 34
  11. 1225 70 35
  12. 1296 72 36

输出

  1. 625 50 25
  2. 676 52 26
  3. 729 54 27
  4. 784 56 28
  5. 841 58 29
  6. 900 60 30
  7. 961 62 31
  8. 1024 64 32
  9. 1089 66 33
  10. 1156 68 34
  11. 1225 70 35
  12. 1296 72 36
  1. public class TestFormat {
  2. public static void main(String[] args) {
  3. for(int i = 25; i<50;i++) {
  4. int sum = i * i;
  5. int add = i + i;
  6. int div = (i+i)/2;
  7. System.out.println("\t" + sum + "\t\t" + add + "\t\t" + div);
  8. }
  9. }
  10. }
英文:

How can I format these columns of numbers properly? Meaning all numbers should be aligning with each other in columns.

I tried to use format but still couldn't fix the alignment. Like :

  1. 625 50 25
  2. 676 52 26
  3. 729 54 27
  4. 784 56 28
  5. 841 58 29
  6. 900 60 30
  7. 961 62 31
  8. 1024 64 32
  9. 1089 66 33
  10. 1156 68 34
  11. 1225 70 35
  12. 1296 72 36

Output

  1. 625 50 25
  2. 676 52 26
  3. 729 54 27
  4. 784 56 28
  5. 841 58 29
  6. 900 60 30
  7. 961 62 31
  8. 1024 64 32
  9. 1089 66 33
  10. 1156 68 34
  11. 1225 70 35
  12. 1296 72 36
  1. public class TestFormat {
  2. public static void main(String[] args) {
  3. for(int i = 25; i<50;i++) {
  4. int sum = i * i;
  5. int add = i + i;
  6. int div = (i+i)/2;
  7. System.out.println("\t" + sum + "\t\t" + add + "\t\t" + div);
  8. }
  9. }
  10. }

答案1

得分: 2

你可以使用System.out.printf,并带有左对齐标志-

// 每个列左对齐6个字符
System.out.printf("%-6d %-6d %d%n", sum, add, div);

查看格式化教程获取更多详细信息。

英文:

You could use System.out.printf with left-justified flag -:

  1. // 6 chars left justified for each column
  2. System.out.printf("%-6d %-6d %d%n", sum, add, div);

See formatting tutorial for more details

huangapple
  • 本文由 发表于 2020年7月29日 02:34:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/63140677.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定