弄清楚如何格式化打印

时间:2014-11-25 08:09:45

标签: java arraylist printf

我无法弄清楚如何从arraylist格式化我的打印, 我只是不知道该怎么做。任何可能有用的提示或片段?谢谢

protected void printTable(ArrayList<double[]> table)
{
    String s = "";
    System.out.printf("\n_____________________________________________________\n");
    System.out.printf("\n  x\t   f[]\t    f[,]    f[,,]    f[,,,]   ");
    System.out.printf("\n_____________________________________________________\n");
    for(int a = 0; a < table.size(); a++)
    {
        System.out.printf("%.3s", s);
        for(double c : table.get(a))
        {
            System.out.printf("%.3f\t " , c);
        }
        System.out.println();
    }
}

目前这样打印:

    _____________________________________________________
    x      f[]      f[,]    f[,,]    f[,,,]   
    _____________________________________________________
    1.000    1.500   0.000   2.000   
    3.000    3.250   3.000   1.670   
    0.500    0.167   -0.665  
    0.333    -1.663  
    -1.997   

我该如何做?

_____________________________________________________

x      f[]      f[,]    f[,,]    f[,,,]   
_____________________________________________________
1.000    3.000   0.500   0.333   -1.997
1.500    3.250   0.167   -1.663  
0.000    3.000   -0.665  
2.000    1.670   

3 个答案:

答案 0 :(得分:2)

您可以使用--flag

来证明您的列
System.out.printf("%-.3f\t " , c);

您可以使用指定宽度(将10宽度更改为您想要的任何宽度)

System.out.printf("%-10.3f " , c);

我建议您删除\t,然后使用宽度和精度标记控制宽度(上例中为10.3

您可以使用二维数组而不是数组的ArrayList来控制打印的顺序

double table [][];

答案 1 :(得分:0)

protected void printTable(ArrayList<double[]> table)
{
    String s = "";
    System.out.printf("\n_____________________________________________________\n");
    System.out.printf("\n  x\t   f[]\t    f[,]    f[,,]    f[,,,]   ");
    System.out.printf("\n_____________________________________________________\n");
    for(int i = 0; i < table.size(); i++) {
        for(int a = 0; a < table.size(); a++)
        {
            if ( table.get(a).length > i ) {
                System.out.printf("%.3f\t " , table.get(a)[i]);
            }
        }
        System.out.println();
    }
}

答案 2 :(得分:0)

下面的代码为你的场景旋转了矩阵,但是我只检查了一个nXn矩阵,你应该能够解决它。

    public void printTable(ArrayList<double[]> table)
{
    String s = "";
    System.out.printf("\n_____________________________________________________\n");
    System.out.printf("\n  x\t   f[]\t    f[,]    f[,,]    f[,,,]   ");
    System.out.printf("\n_____________________________________________________\n");
    int i =0;

    for(int a = 0; a < table.size(); a++)
    {
        System.out.printf("%.3s", s);
        for(int j= 0;j<table.size();j++){
            double[] d = table.get(j);

            for(int k =a;k<=a;k++){
                System.out.printf("%.3f\t " , d[k]);
            }
        }
        System.out.println();
    }
}