如何在控制台输出上对齐字符串 [英] How to align String on console output

查看:248
本文介绍了如何在控制台输出上对齐字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须为以下内容编写代码:





我写了代码:

  public class tables {
public static void main(String [] args){
// int [] [] table = new int [12] [12];
String table =;
for(int i = 1; i <13; i ++){
for(int j = 1; j <13; j ++){
// table [i-1] [j -1] = i * j;
table + =(i * j)+;
}
System.out.println(table.trim());
table =;
}
}
}

但问题是输出格式。我需要一个像时尚矩阵的输出,每个数字格式化为4的宽度(数字是右对齐,并剥离每行的前/后空格)。我试过 google ,但找不到任何好的解决我的问题。

解决方案

可以使用 format()根据需要设置输出格式。

  for(int i = 1; i <13; i ++){
for(int j = 1; j< 13; j ++){

System.out.format(%5d,i * j);
}
System.out.println(); //移动到下一行。
}

或者,您也可以使用: -

  System.out.print(String.format(%5d,i * j)); 

代替 System.out.format ..



以下是如何%5d 工作的说明:首先,因为我们打印整数,我们应该使用%d 这是格式说明符 c>%5d 表示整数的总宽度。 输出将采取..所以,如果你的值是5,它将被打印覆盖5个空间,像这样: - **** 5

  • %5d 用于右对齐。对于左对齐,您可以使用% - 5d 。对于值 5 ,这将打印您的输出: - 5 ****


  • I've to write code for:

    I'd written the code:

    public class tables {
        public static void main(String[] args) {
            //int[][] table = new int[12][12];
            String table="";
            for(int i=1; i<13; i++){
                for(int j=1; j<13; j++){
                    //table[i-1][j-1] = i*j;
                    table+=(i*j)+" ";
                }
                System.out.println(table.trim());
                table="";
            }
        }
    }
    

    But the problem is with the output format. I need the output in a matrix like fashion, each number formatted to a width of 4 (the numbers are right-aligned and strip out leading/trailing spaces on each line). I'd tried google but not find any good solution to my problem. Can anybody help me out?

    解决方案

    You can use format() to format your output according to your need..

        for(int i=1; i<13; i++){
            for(int j=1; j<13; j++){
    
               System.out.format("%5d", i * j);
            }
            System.out.println();  // To move to the next line.
        }
    

    Or, you can also use: -

    System.out.print(String.format("%5d", i * j));
    

    in place of System.out.format..

    Here's is the explanation of how %5d works: -

    • First, since we are printing integer, we should use %d which is format specifier for integers..
    • 5 in %5d means the total width your output will take.. So, if your value is 5, it will be printed to cover 5 spaces like this: - ****5
    • %5d is used to align right.. For aligning left, you can use %-5d. For a value 5, this will print your output as: - 5****

    这篇关于如何在控制台输出上对齐字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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