How to print align with my display [duplicate]

2019-02-21 06:32发布

This question already has an answer here:

for (int j = 0; j < numStu; j++) {  

System.out.println((j + 1) + "\t" + StudentName[j] + "\t\t\t" + (Marks[j]) + "\t" + Grade[j]);  

} 


No. Name            Marks   Grade
1   ADRIAN TAN          46.00   C-
2   KIM CHEE LIONG HAN          76.00   A-
3   PETER LIM AH MENG           64.00   B-
4   WAYNE WALKER            23.00   F

Sorry for previous question >< This is my output for the command above. The desired output is:

No. Name                   Marks    Grade
1   ADRIAN TAN             46.00    C-
2   KIM CHEE LIONG HAN     76.00    A-
3   PETER LIM AH MENG      64.00    B-
4   WAYNE WALKER           23.00    F

2条回答
看我几分像从前
2楼-- · 2019-02-21 07:05

Say X is the length you want, then use String.format("%-Xs",argument). This will cut or extend the string to X length. The - after the % sign says to add the spaces after the string. If you ommit the - sign, it will still work but looks wierd.

Here is an example

String[] name = {"Ben", "Jacob", "Tyler"};
        int[] age = {5, 16, 25};
        int[] salary = {0, 1000, 100000};
        System.out.printf("No.\t%-10s\t%-10s\t%-10s\n", "Name", "Age", "Salary");
        for (int i = 0; i < name.length; i++) {
            System.out.println(String.format("%-3d\t%-10s\t%-10d\t%-10d", i, name[i], age[i], salary[i]));
        }

Edit: changed from String.format("%-X.Xs",argument) to String.format("%-Xs",argument)

查看更多
放我归山
3楼-- · 2019-02-21 07:10

Hmm do u mean that?:

for (int j = 0; j < numStu; j++) {  
System.out.println("\n" + (j + 1) + " " + StudentName[j] + "\t" + (Marks[j]) + "\t" +     Grade[j]);}  

It should do a thing

查看更多
登录 后发表回答