Java Program to display employee data in tabular format on console.
Objective
Write a Java program to display a 2D array of Employee data in a formatted console table.
Algorithm / Approach
- Create a 2D String array containing IDs and Names.
- Use loops and print statements to draw the top border (
+------------------+). - Iterate through the array rows.
- For the name column, use
String.format("%-10s", name)to left-align the string and pad it with spaces up to 10 characters. - Print the vertical borders (
|) around the data. - Draw the bottom border.
EmpTable.java
class EmpTable
{
public static void main(String [] ar)
{
String[][] emps = {
{"1001","Scott"},
{"1002","Michel"},
{"1003","Cruise"},
{"1004","Brosnan"}
};
System.out.print("+");
for(int i=0;i<18;i++)
System.out.print("-");
System.out.println("+");
String n;
for(int j=0;j<4;j++)
{
System.out.print("| "+emps[j][0]);
n=String.format("%-10s",emps[j][1]);
System.out.println(" | "+n+"|");
}
System.out.print("+");
for(int i=0;i<18;i++)
System.out.print("-");
System.out.println("+");
}
}
Expected Output
+------------------+ | 1001 | Scott | | 1002 | Michel | | 1003 | Cruise | | 1004 | Brosnan | +------------------+
Explanation of the Program
- Console applications don't have GUI tables, so you must use ASCII art formatting to make data readable.
- The format specifier
%-10sis the key to aligning the columns perfectly. The-forces left-alignment, and the10ensures that no matter how short the name is, it will consume exactly 10 spaces.
Complexity
Time Complexity
O(n) - Where n is the number of employees.
Space Complexity
O(1)