我正在尝试为成绩报告编制表格,该报告应包含5列,分别是“类别”,“说明”,“单位”,“成绩”和“成绩点”。 但是,我无法使输出彼此对齐。 我只是使用“ \ t”。 有没有办法在Java中将输出制成表格?
import java.util.*;
public class Project1_Trial2 {
public static void main(String args[])
{
Scanner scanner = new Scanner(System.in);
//Input the term
System.out.println("Please enter the term of your grade calculation (for example, Fall 2015): ");
String term = scanner.nextLine();
//Input the number of courses that the student is enrolled in
System.out.println("Please enter the number of courses that you are enrolled in "+term+": ");
int numberofcourses = scanner.nextInt();
//Declaration
String ClassName[] = new String[numberofcourses];
String Description[] = new String[numberofcourses];
String Grade[] = new String[numberofcourses];
int Units[] = new int[numberofcourses];
//Arrays for class number, description, units, grade, grades point
//Here, input class number, description, units, and grades
for(int i = 0; i < numberofcourses; i++)
{
scanner.nextLine();
System.out.println("Please enter your #"+(i+1)+" class name: ");
ClassName[i] = scanner.nextLine();
System.out.println("Please enter your #"+(i+1)+" class description: ");
Description[i] = scanner.nextLine();
System.out.println("Please enter your #"+(i+1)+" class units: ");
Units [i] = scanner.nextInt();
System.out.println("Please enter your #"+(i+1)+" class grade: ");
Grade[i] = scanner.nextLine();
}
System.out.println("Class Grades - "+term+" Term");
System.out.println("Office Grades");
System.out.println("Class \t \t Description \t \t Units \t \t Grade \t \t Grade Points");
for(int i = 0; i < numberofcourses; i++)
{
System.out.println(ClassName[i]+"\t \t"+Description[i]+"\t \t"+Units[i]+"\t \t"+Grade[i]);
}
}
}
答案 0 :(得分:1)
有多种方法可以对齐输出,以便它们均匀对齐。...一种方法是替换放置位置:
System.out.println(ClassName[i]+"\t \t"+Description[i]+"\t \t"+Units[i]+"\t \t"+Grade[i]);
具有:
System.out.printf("%-15s %-15s %-15s ",ClassName[i],Description[i],String.format("%5d", Units[i]),Grade[i]);
代替使用System.out.println()
,而是使用System.out.printf()
来填充字符串,并在String.format()
函数内部使用printf()
来用空格填充整数...您可以调整我的填充物以适合您的感觉
这是一种更有效的方法,而不是经常使用标签页