问题
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
回答1:
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)
回答2:
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
来源:https://stackoverflow.com/questions/23757856/how-to-print-align-with-my-display