【问题标题】:Aligning numbers in a table对齐表格中的数字
【发布时间】:2013-07-12 18:10:38
【问题描述】:

表格应该是这样的:

我的表产生了正确的输出。只需要在水平侧对齐值即可。

import java.util.Scanner;

公开课很无聊

{ public static void main(String[] args)

{
    Scanner keyboard = new Scanner (System.in);

    int rows=0, cols=0;
    int a, b;

    System.out.print("Enter number of rows from 1-10");


    rows = keyboard.nextInt();

    System.out.print("Enter number of columns from 1-10");

    cols = keyboard.nextInt();

    for (int c=1; c<=cols; c++){
        System.out.print("    "+c);

    }
    System.out.println(); 
    System.out.println(    "----------------------");

    for (int d=1; d<=rows;d++){
        System.out.print(""+d);
        System.out.println(); 

    }

    for ( a=1; a<=rows; a++) 
    {

        for ( b=1; b<=cols; b++)
        {


            System.out.print("    "+a*b);
        }
        System.out.println(); 


    }
}

}

【问题讨论】:

标签: java alignment


【解决方案1】:

进行填充(左或右)的最简单和最有效的方法是使用String.format() 方法。

左填充 8 个空格:

String.format("% 8d", yournumber);

【讨论】:

    【解决方案2】:

    在处理表格时,您绝对不能只依赖空格和 \t(制表符的转义字符)。这些被认为是无用的方式,因为它们可能会根据程序中的额外信息而改变。

    我建议学习如何使用 printf()

    System.out.printf();
    

    这几乎在任何处理表格和对齐特定信息的情况下都使用。

    System.out.printf() training

    【讨论】:

      猜你喜欢
      • 2011-01-23
      • 2012-08-29
      • 1970-01-01
      • 2018-04-19
      • 1970-01-01
      • 2022-11-28
      • 2013-11-27
      • 2017-12-16
      • 2017-01-23
      相关资源
      最近更新 更多